对原生ajax的简单封装

1.引用类型Http

'use strict';

//引用类型Http,封装了ajax异步调用get和post方法
function Http() {
    this.xhq = null;
}

//启动http中get请求,以备发送
Http.prototype.get = function (url, query, option) {
    this.request('get', url, query, null, option);
    return this;
}

//启动http中post请求,以备发送
Http.prototype.post=function(url,option){
    this.request('post',url,null,null,option);
    return this;
}

//发送http请求的通用方法
Http.prototype.request = function (method, url, query, option) {
    this.xhq=new XMLHttpRequest();
    var url = this.addQuery(url, query);
    //console.log(url);
    this.xhq.open(method, url, true);

    for (var i in option) {
        this.xhq.setRequestHeader(i, option[i]);
    }
    return this;
}

//获取响应成功后执行
Http.prototype.success=function(success){
    this.then(success);
    return this;
}

//获取响应失败后执行
Http.prototype.fail=function(fail){
    this.then(fail);
    return this;
}

//获取响应后,根据响应结果执行相应操作
Http.prototype.then = function (success,fail) {
    var xhq=this.xhq;
    xhq.addEventListener('readystatechange',function(){
         if (xhq.readyState === 4) {
            if (xhq.status >= 200 && xhq.status < 300 || xhq.status == 304) {
                if (typeof success === 'function') {
                    success(xhq.status, xhq.responseText);
                }
            } else {
                if (typeof fail === 'function') {
                    fail(xhq.status, xhq.responseText);
                }
            }
        }
    });
    return this;
}

//发送相应请求
Http.prototype.send=function(data){
    this.xhq.send(JSON.stringify(data));
}

//为url添加查询字符串辅助方法
Http.prototype.addQuery = function (url, data) {
    for (var i in data) {
        url += (url.indexOf('?') === -1 ? '?' : '&');
        url += encodeURIComponent(i) + '=' + encodeURIComponent(data[i]);
    }
    return url;
}

2.测试代码

var http=new Http();
http.request('get','text.json',null,{key: 'value'})
    .then(function(status,data){
        console.log(data);
    },function(status,data){
        console.log(status);
    })
    .success(function(status,data){
        console.log(status);
    })
    .send(null);

http.post('text.json',{name: 'jc',num: 1})
    .then(function(status,data){
        console.log(data);
    },function(status,data){
        console.log(status);
    })
    .success(function(){
        console.log('ready');
    })
    .send({name: 'jc',num: 1});
  • 红宝书中提到,必须在调用open之前指定readystatechange事件处理程序才能确保浏览器兼容性,这里为了能够链式调用在open之后通过DOM2级方法绑定了多个事件处理程序,在chorme下测试通过,应该还有更好的实现方法
  • 在过程函数中返回this对象自身的引用达成链式调用,但是并没有检查输入参数的类型,可能会导致问题
  • 可以使用anywhere搭建一个简单的本地服务器,测试ajax方法
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容