美文网首页
mini ajax函数

mini ajax函数

作者: TOPro | 来源:发表于2018-05-23 17:51 被阅读16次
export default function(url,method="POST",option){
    option = option || {};
    var xhr = new XMLHttpRequest();
    Object.keys(option.headers||{}).forEach(key=> xhr.setRequestHeader(key,option.headers[key]));
    let paramsString="";Object.keys(option.params||{}).forEach(key=>paramsString+=("&"+key+"="+option.params[key]));
    xhr.open(method, url+"?"+paramsString.substr(1));
    return new Promise((resolve,reject)=>{
        var timeout = setTimeout(function(){
            let _xhr ={};Object.keys(xhr.__proto__).forEach(key=>_xhr[key]=xhr[key]);
            _xhr.response = {'message':'超时'};
            reject(_xhr)
        },option.timeout||10000);
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4) {
                let _xhr ={};Object.keys(xhr.__proto__).forEach(key=>_xhr[key]=xhr[key]);
                try {_xhr.response = JSON.parse(_xhr.response)}catch (e) {}
                clearTimeout(timeout);
                resolve(_xhr)
            }
        }
        xhr.send(option.data||{});
    })
}

相关文章

网友评论

      本文标题:mini ajax函数

      本文链接:https://www.haomeiwen.com/subject/kjqdjftx.html