原生的ajax请求的写法

//get请求
var xhr=new XMLHttpRequest();
xhr.open("GET","[请求路径]",true);
xhr.setRequestHeader("If-Modified-Since","0");//设置浏览器不使用缓存
xhr.onreadystatechange=function(){//处理函数
     if(xhr.readyState==4)
     {
            if(xhr.status==200)
             {
             //处理数据
             var returnData=xhr.responseText;
             }
         else
         {
             alert("服务器错误!"+ajax.status);
             }
     }
};
xhr.send(null);


//post请求
var xhr=new XMLHtmlRequest();//创建异步请求对象
xhr.open("POST","[请求路径]",true);
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.onreadystatechange=function(){
    if(xhr.readyState==4){
        if(xhr.status==200){
                var returnDate=xhr.responseText;
            }
            }
    };
xhr.send("parameterA=a&parameterB=b");

readystatus的五个状态:

0未初始化,new完后。

1已打开。对象已经创建并初始化,但还未调用send方法。

2已发送,已经调用send方法,但该对象正在等待状态码和头的返回。

3正在接受。已经接受了部分数据,但还不能使用该对象的属性和方法,因为状态和相应头不完整。

4已加载,所有数据接受完毕。

 

浏览器兼容的创建异步对象的方法:

            function createXmlHttp() {//创建xhr对象
                var xhobj = false;
                try {
                    xhobj = new ActiveXObject("Msxml2.XMLHTTP"); // ie msxml3.0+
                } catch (e) {
                    try {
                        xhobj = new ActiveXObject("Microsoft.XMLHTTP"); //ie msxml2.6
                    } catch (e2) {
                        xhobj = false;
                    }
                }
                if (!xhobj && typeof XMLHttpRequest != 'undefined') {// Firefox, Opera 8.0+, Safari
                    xhobj = new XMLHttpRequest();
                }
                return xhobj;
            }

 

posted @ 2012-07-01 18:36  王伟1989  阅读(344)  评论(0)    收藏  举报