封装兼容的Ajax请求

XMLHttpRequest对象

XMLHttpRequest 对象提供了对 HTTP 协议的完全的访问,包括做出 POST 和 HEAD 请求以及普通的 GET 请求的能力。
XMLHttpRequest 对象是Ajax请求的基础。

AJAX请求

var xhr = new XMLHttpRequest();

xhr.open('get/post', 'url地址', 'ture/false'); //   请求方式/地址/是否异步
xhr.send(null);

//监听状态改变和接收数据
xhr.onreadystatechange = function() {
    //readyState == 4 发送完成
    //status >= 200  接收完成
    if(xhr.readyState == 4 && xhr.status == 200) {
        var data = xhr.responseText;
    }
}

封装一个兼容的AJAX请求

function createXHR() {
    if(window.XMLHttpRequest) {
        return new XMLHttpRequest();
    }
    return new ActiveXObject(); //IE6-
}

//obj {name:huhu,age:18}  => "name=huhu&age=18"
function params(obj) {
    var arr = [];
    for(var i in obj) {
        var str = i + "=" + obj[i];
        arr.push(str);
    }
    return arr.join("&");
}

function ajax(obj) {
    var xml = createXHR();
    obj.data = params(obj.data);

    //get请求把参数添加到url后面
    if(/get/i.test(obj.method)) {
        obj.url += obj.data.length > 0 ? ("?" + obj.data) : "";
    }

    xhr.open(obj.method, obj.url, obj.async);
    if(/get/i.test(obj.mothod)) {
        xml.send(null);
    } else {
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.send(obj.data);
    }

    if(obj.async) {
        xhr.onreadystatechange = function() {
            if(xhr.readyState == 4) {
                callback();
            }
        }
    } else {
        callback(); //同步
    }

    function callback() {
        if(xhr.status == 200) {
            obj.success(xhr.responseText);
        } else {
            obj.error(xhr.status);
        }

    }

}

//使用
ajax({
    method: 'xxx',
    url: 'XXX'
    params: {
        name: huhu,
        age: 18
    },
    async: true
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值