当前位置: 移动技术网 > IT编程>开发语言>JavaScript > jQuery异步对象(XMLHttpRequest)解析

jQuery异步对象(XMLHttpRequest)解析

2019年03月27日  | 移动技术网IT编程  | 我要评论

我们先来看看异步对象五部曲

这是post请求的、

 

代码如下:


 //1.00创建异步对象
            var xhr = new xmlhttprequest();
            //2.0
            xhr.open("post", url,params, true);
            //3.0将参数使用formdata属性传递
            xhr.setrequestheader("content-type", "application/x-www-form-urlencoded");
            //4.0设置回调函数
            xhr.onreadystatechange = function () {
                if (xhr.readystate == 4 && xhr.status == 200) {
                    alert(xhr.responsetext);
                }
            }
            //5.0传递参数
            xhr.send(params);

 

结合get请求做一个异步对象的封装

get 请求中的

  xhr.setrequestheader("if-modified-since", "0"); 是为了清除缓存

而post请求的

 

代码如下:


 xhr.setrequestheader("content-type", "application/x-www-form-urlencoded");

 

是为了传输方式
在<from method='post' type="">
<from>中的type可以得到三种方式,其中包括application/x-www-form-urlencoded
 

代码如下:


var ajaxhelp = {
    creatxhr: function () {
        //创建异步对象
        var xhr = new xmlhttprequest();
        return xhr;
    },
    //ajax的get请求
    ajaxget: function (url, callback) {
        this.ajaxcommon("get", url, null, callback);
    },
    //ajax的post请求
    ajaxpost: function (url, params, callback) {
        this.ajaxcommon("post", url, params, callback);
    },
    ajaxcommon: function (method, url, params, callback) {
        //1.0
        var xhr = this.creatxhr();
        //2.0
        xhr.open(method, url, true);
        //3.0
        if (method == "get") {
            xhr.setrequestheader("if-modified-since", "0");
        } else {
            xhr.setrequestheader("content-type", "application/x-www-form-urlencoded");
        }
        //4.0
        xhr.onreadystatechange = function () {
            if (xhr.readystate == 4 && xhr.status == 200) {
                var datas = json.parse(xhr.responsetext);
                //执行回调函数
                callback(datas);
            }
        }
        //5.0
        xhr.send(params);
    }
};

 

ps:在jquery里面是有$.ajax  和$.get /   $.post  等异步请求的方法的。以前的封装就不用了。额。好扯。其实他们底层也是这样的写的呢。jquery就是为了解决各个的兼容性问题而已

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网