用Ajax封裝get和post

參考:http://www.itdecent.cn/p/a7eea5768dad

封裝get

function get(url,options,callback){
    var xhr = new XMLHttpRequest();
       xhr.onreadystatechange = function(callback) {
        if (xhr.readyState == 4) {
            if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
                callback(xhr.responseText);
            } else {
                alert('Request was unsuccessful:' + xhr.status);
            }
        }
    }
    function serialize(options) {
        if(!options){
            return '';
        }

        var pairs = [];
        for(var name in options){
            if(!options.hasOwnProperty(name)){
                continue;
            }
            if(typeof options[name] === 'function'){
                continue;
            }
            var value = options[name].toString();
            name = encodeURIComponent(name);
            value = encodeURIComponent(value);
            pairs.push(name+'='+value);
        }
        return pairs.join('&');
    }

xhr.open('get', url+'?'+serialize(options),true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(null);
 }
get('/information', {     //數(shù)據(jù)驗證
    name: 'netease',
    age: 18
},
function(data) {
    console.log(data);
});

封裝post

function post(url, options, callback) {
if(XMLHttpRequest){
var xhr=new XMLHttpRequest();
}else{
var xhr=new ActiveXObject("Microsoft.XMLHTTP");//兼容ie
}

xhr.onreadystatechange = function(callback) {
    if (xhr.readyState == 4) {
        if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
            callback(xhr.responseText);
        } else {
            alert('Request was unsuccessful:' + xhr.status);
        }
    }
}

function serialize(options) {
    if (!options) {
        return '';
    }
    var pairs = [];
    for (var name in options) {
        if (!options.hasOwnProperty(name)) {
            continue;
        }
        if (typeof options[name] === 'function') {
            continue;
        }
        var value = options[name].toString();
        name = encodeURIComponent(name);
        value = encodeURIComponent(value);
        pairs.push(name + '=' + value);
    }
    return pairs.join('&');
}

xhr.open('post', url,true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(serialize(options));
}
post('/post', { //測試數(shù)據(jù)
name: 'netease-post',
age: 20
},
function(data) {
console.log('我是post請求');
});

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

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

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