AJAX基本格式步骤


第一步:创建XMLHttpRequest对象
var xmlhttp;
//兼容性
if (window.XMLHttpRequest)
  {
  xmlhttp=new XMLHttpRequest();
  }
else
  {
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

代码解释:

  1. 首先创建一个作为 XMLHttpRequest 对象使用的 XMLHttp 变量。把它的值设置为 null。
  2. 然后测试 window.XMLHttpRequest 对象是否可用。在新版本的 Firefox, Mozilla, Opera 以及 Safari 浏览器中,该对象是可用的。
  3. 如果可用,则用它创建一个新对象:XMLHttp=new XMLHttpRequest()
  4. 如果不可用,则检测 window.ActiveXObject 是否可用。在 Internet Explorer version 5.5 及更高的版本中,该对象是可用的。
  5. 如果可用,使用它来创建一个新对象:XMLHttp=new ActiveXObject()
 
第二步:确定来自服务器的响应是否XML  ,  async的值
 
1.如果来自服务器的响应并非 XML,请使用 responseText 属性
 ··当使用 async=true 时,请规定在响应处于 onreadystatechange 事件中的就绪状态时执行的函数:
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
 
  ··当您使用 async=false 时,请不要编写 onreadystatechange 函数 - 把代码放到 send() 语句后面即可:
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
 
2.如果来自服务器的响应是 XML,而且需要作为 XML 对象进行解析,请使用 responseXML 属性:
 
xmlDoc=xmlhttp.responseXML;
txt="";
x=xmlDoc.getElementsByTagName("标记");
for (i=0;i<x.length;i++)
  {
  txt=txt + x[i].childNodes[0].nodeValue + "<br />";
  }
document.getElementById("myDiv").innerHTML=txt;
 
第三步:向服务器发送请求:
xmlhttp.open("GET","test1.txt",true);
xmlhttp.send();
 
xmlhttp.open("POST","ajax_test.asp",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");//请求头应在open和send之间
xmlhttp.send("fname=Bill&lname=Gates");
posted @ 2017-09-04 01:07  Cooper_Yao  阅读(948)  评论(0编辑  收藏  举报