自己编写ajax步骤

  编写自己的Ajax  的步骤 

  1.创建XMLHttpRequest对象 (唯一的浏览器依赖性涉及 XMLHttpRequest 对象的创建。在 IE 5 和 IE 6   中,必须使用特定于 IE 的 ActiveXObject() 构造函数)

 2.调用open(get/post, url , true)  

第一个参数可取值get或post;

第二个参数为请求的路径;要是第一个是get  url后面可以跟参数,要是post 不能带有参数

                                             xhr.setRequestHeader(name, value);//设置请求报文头

第三个参数为是否采用异步,使用ajax绝对是true的啦。

3、注册回调函数 

xhr.onreadystatechange = function() { 
     if (xhr.readyState == 4) {//注意此处的readyState的大小写,HTTP 响应已经完全接收

           if (xhr.status == 200) { /当状态为 200 的它是 "OK",当状态为 404 的它是 "NotFound"。
               var res = xhr.responseText;//接收返回的效果 
           document.getElementById("showcontext").innerHTML = res; //将返回的结果赋值

            } 
        } 
}

 4.发送 xhr.send(null) get方法  要是 使用的是 post方法 xhr.send("") 参数名=参数值

  文档案例 创建对象如下

  xmlHttp=null;

if (window.XMLHttpRequest)
  {// code for IE7, Firefox, Opera, etc.
  xmlHttp=new XMLHttpRequest();
  }
else if (window.ActiveXObject)
  {// code for IE6, IE5
  xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
if (xmlHttp!=null)
  {
  xmlHttp.open("GET", "note.xml", false);
  xmlHttp.send(null);
  xmlDoc=xmlHttp.responseText;

  xmlHttp.open("POST", "demo_dom_http.asp", false);
  xmlHttp.send(xmlDoc);
  document.write(xmlHttp.responseText);
  }

  

猜你喜欢

转载自dusai2010.iteye.com/blog/2218544