通过XMLHttpRequest,ActiveXObject实现ajax请求

今天学习了原生的ajax请求。我将涉及到的ajax请求方法封装成了一个对象:

var xhr={
    getXHR:function(){
        var XHR = null;
        if(typeof window.ActiveXObject != 'undefined'){
            XHR = xhr.createActiveXObject();
        }else{
            XHR = xhr.createStandardXHR();
        }
        return XHR;
    },
    createActiveXObject:function(){
        try{
            return new window.ActiveXObject("Mscrosoft.XMLHttp");
        }catch(e){}
    },
    createStandardXHR:function(){
        try{
            return new window.XMLHttpRequest();
        }catch(e){}
    },

    onreadystatechange:function(xhr,callback){
        if(!callback){return;}
        if(xhr.readyState == 4){
            if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
                callback(xhr.responseText);
            }
        }
    },
    //IE8+
    ontimeout:function(callback){
        if(!callback){return;}
        callback();
    },
    onprogress:function(event,callback){
        console.log("dsss");
        if(!callback){return;}
        callback(event);
    }
};

 

发送一个请求:

var XHR = xhr.getXHR();
    XHR.onreadystatechange=xhr.onreadystatechange(function(data){
    console.log(data);
    });

    XHR.timeout=10000;

    XHR.ontimeout = xhr.ontimeout(function(){
        alert("timeout");
    });

    XHR.onprogress = xhr.onprogress(function(event){
        console.log(event.totalSize);
    });

    XHR.open("get","url",true);
    XHR.send(null);


open方法接收三个参数,请求类型,请求url,是否是异步。

当为异步请求时,XHR的readystate属性有以下属性值:

当为0时,即表示没有调用open()方法;

当为1时,此时已经调用了open()方法;

当为2时,此时已经调用了send()方法;

当为3时,此时已经有部门的数据相应了;

当为4时,此时数据已经全部相应,而且可以在客户端使用了;

 

每次readyState的值改变,都会触发一次onreadystatechange事件,因此要在调用open()之前指定onreadystatechange事件以便判断是否已经响应完成且可以使用数据了。

对onreadystatechange事件的处理程序为:

 

 onreadystatechange:function(xhr,callback){
        if(!callback){return;}
        if(xhr.readyState == 4){
            if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
                callback(xhr.responseText);
            }
        }
    },

首选检测是否已经接收了全部响应数据,因此需要判断xhr.readyState的值是否为4;

当响应完成后,响应结果存在多种,有的是500失败了,有的是404未找到等等。因此需要根据返回的状态status的值来判断响应是否成功。当status为304时,表示的是该资源缓存了,直接取的缓存数据。

 

XHR.send(null) :发送请求,当没有参数传递时,参数为null;当为get请求时,携带的参数需要通过encodeURIComponent进行编码。

也可以自定义请求的头部信息,在send()与open()方法之间进行设置:

XHR.sendRequestHeader(key,value);

 

 

 

 

 

 

posted @ 2014-11-05 19:37  爱生活者wmmang  Views(2839)  Comments(0Edit  收藏  举报