为了账号安全,请及时绑定邮箱和手机立即绑定

原生JavaScript写的Ajax方法

标签:
JavaScript
/*  示例:
    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("&")}
点击查看更多内容
3人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消