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||{});
})
}
网友评论