继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

原生JavaScript写的Ajax方法

hhhzihao2
关注TA
已关注
手记 3
粉丝 1
获赞 33
/*  示例:
    ajax({
        //async: true,      // 默认是 true(异步)
        //headers: {},      // 额外的"{键:值}"对映射到请求一起发送,仅限 POST
        //type: "GET",      // 默认是 GET
        //dataType: "json", // 默认是 json
        url: "./TestXHR.php",
        data: { name: "super", age: 20 },
        success: function (response, xml) {
            // console.log(status);
        },
        error: function (status) {
            console.log(status);
            console.log('ajax error');
        }
    });
*/
function ajax(o) {
    if (typeof(o) != 'object' || typeof(o.url) != 'string') return;
    o.type = (o.type || 'GET').toUpperCase();
    o.dataType = (o.dataType || 'json').toLowerCase();
    o.headers = o.headers || {};
    var t = typeof(o.async);
    o.a = t == 'undefined' ? true: t == 'string' ? o.async.toLowerCase() != 'false': Boolean(o.async);
    var params = formatParams(o.data);
    var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
    xhr.onreadystatechange = function() {
        if (xhr.readyState != 4) return;
        var status = xhr.status;
        if (status >= 200 && status < 300) {
            if (!o.success) return;
            if (o.dataType != 'json') o.success(xhr.responseText, xhr.responseXML);
            else try {
                o.success(JSON.parse(xhr.responseText), xhr.responseXML)
            } catch(e) {
                o.success(xhr.responseText, xhr.responseXML)
            }
        } else if (o.error) o.error(status)
    };
    if (o.type == "GET") {
        xhr.open("GET", o.url + "?" + params, o.a);
        xhr.send(null)
    } else if (o.type == "POST") {
        xhr.open("POST", o.url, o.a);
        for (var k in o.headers) {
            xhr.setRequestHeader('"' + k + '"', '"' + o.headers[k] + '"');
            k.toLowerCase() == 'content-type' && (o.c=true);
        }
        typeof(o.c)=='undefined' && xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.send(params)
    }
}
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("&")
}

下面是压缩版

function ajax(o){if(typeof(o)!='object'||typeof(o.url)!='string')return;o.type=(o.type||'GET').toUpperCase();o.dataType=(o.dataType||'json').toLowerCase();o.headers=o.headers||{};var t=typeof(o.async);o.a=t=='undefined'?true:t=='string'?o.async.toLowerCase()!='false':Boolean(o.async);var params=formatParams(o.data);var xhr=XMLHttpRequest?new XMLHttpRequest():new ActiveXObject('Microsoft.XMLHTTP');xhr.onreadystatechange=function(){if(xhr.readyState!=4)return;var status=xhr.status;if(status>=200&&status<300){if(!o.success)return;if(o.dataType!='json')o.success(xhr.responseText,xhr.responseXML);else try{o.success(JSON.parse(xhr.responseText),xhr.responseXML)}catch(e){o.success(xhr.responseText,xhr.responseXML)}}else if(o.error)o.error(status)};if(o.type=="GET"){xhr.open("GET",o.url+"?"+params,o.a);xhr.send(null)}else if(o.type=="POST"){xhr.open("POST",o.url,o.a);for(var k in o.headers){xhr.setRequestHeader('"'+k+'"','"'+o.headers[k]+'"');k.toLowerCase()=='content-type'&&(o.c=true)}typeof(o.c)=='undefined'&&xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");xhr.send(params)}}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("&")}
打开App,阅读手记
3人推荐
发表评论
随时随地看视频慕课网APP