原生JS AJAX實(shí)現(xiàn)

AJAX說明

  • IE7及其以上版本中支持原生的 XHR 對(duì)象,因此可以直接用:new XMLHttpRequest();
  • IE6及其之前的版本中,XHR對(duì)象是通過MSXML庫中的一個(gè)ActiveX對(duì)象實(shí)現(xiàn)的。則:new ActiveXObject('Microsoft.XMLHTTP');

實(shí)現(xiàn)

function ajax(options) {
    options = options || {};
    options.type = (options.type || "GET").toUpperCase();
    options.async = options.async || true;
    var params = formatParams(options.data);
    //若IE9以上,支持ES5,則可用以下方法快捷格式化參數(shù)
    //var qs = Object.keys(data).reduce(function(pre,cur,index){
    //   return pre + '&' + encodeURIComponent(cur) + '=' + encodeURIComponent(data[cur]);
    //},'');
    //var params = qs.slice(1);

    //創(chuàng)建xhr - 非IE6/IE6及其以下版本瀏覽器
    var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');

    //接收 - 第三步
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            var status = xhr.status;
            if (status >= 200 && status < 300) {
                options.success && options.success(xhr.responseText, xhr.responseXML);
            } else {
                options.fail && options.fail(status);
            }
        }
    }

    //連接 和 發(fā)送 - 第二步
    if (options.type == "GET") {
        xhr.open("GET", options.url + "?" + params, options.async);
        xhr.send(null);
    } else if (options.type == "POST") {
        xhr.open("POST", options.url, options.async);
        //設(shè)置表單提交時(shí)的內(nèi)容類型
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.send(params);
    }
}
//格式化參數(shù)
function formatParams(data) {
    var arr = [];
    for (var name in data) {
        arr.push(encodeURIComponent(name) + "=" + encodeURIComponent(data[name]));
    }
    arr.push(("v=" + Math.random()).replace(".", ""));
    return arr.join("&");
}
//調(diào)用方法
ajax({
    url: "url",              //請(qǐng)求地址
    type: "POST",                       //請(qǐng)求方式
    data: { a: "test", b: "t" },        //請(qǐng)求參數(shù)
    success: function (response, xml) {
        // 此處放成功后執(zhí)行的代碼
    },
    fail: function (status) {
        // 此處放失敗后執(zhí)行的代碼
    }
});

大前端知識(shí)庫收集分享 www.rjxgc.com 壹玖零Tech
搜羅各種前后端奇淫技巧,花式編程思想,日日更新,速來圍觀吧...

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容