var dftXHR = {
url: null
,method: 'POST'
,data: {}
,async: true
,dataType:''
,header:{
'Content-Type':'application/x-www-form-urlencoded; charset=utf-8'
}
,progress:function(){}
,before: function(){}
,complete: function(){}
,success: function(){}
,fail: function(){}
}
function isPlainObject(obj){
if(!obj || typeof obj != 'object'){return false;}
if(obj.constructor.prototype.hasOwnProperty("isPrototypeOf")){
return true;
}
return false;
}
var sendxhr = function(options){
let setting = Object.assign({},dftXHR,options)
,contentType = isPlainObject(setting.contentType)
,xhr = new XMLHttpRequest()
,method = setting.method.toUpperCase()
,getQueryStr = method == 'GET' && /.+\?(.+)$/.exec(setting.url)[1] || ''
,setParams = function() {
xhr.timeout = 25000;
xhr.responseType = setting.dataType
xhr.open(method,setting.url+getQueryStr,setting.async)
let header = setting.header
for(let key in header){
xhr.setRequestHeader(key,header[key]);
}
method == 'POST' && !'Content-Type' in header && xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=utf-8')
}()
,evtListener = function(){
xhr.addEventListener('loadstart', function(){
setting.before(xhr);
});
xhr.addEventListener('progress',function(e){
if(e.lengthComputable){
setting.progress.call(xhr,e,e.loaded,e.total)
}
})
xhr.addEventListener('readystatechange',function(){
if(xhr.readyState === 4 && (xhr.status >= 200 && xhr.status < 300 || xhr.status==304)){
setting.success.call(xhr,xhr.response,xhr.status)
}else{
setting.fail.call(xhr,xhr.status,xhr.statusText)
}
})
xhr.addEventListener('loadend',function(){
setting.complete.call(xhr,xhr.status,xhr.statusText)
})
xhr.addEventListener('error',function(){
setting.fail.call(xhr,xhr.status,xhr.statusText)
})
xhr.addEventListener('timeout',function(){
setting.fail.call(xhr,xhr.status,xhr.statusText)
xhr.abort();
})
}()
,assembleQueryStr = function(obj){
let args = "";
Object.keys(obj).forEach(function(key){
let val = obj[key]||''
args += key+"="+decodeURIComponent(val)+"&";
});
return args.substring(0,args.length-1);
}
xhr.send(assembleQueryStr(setting.data));
}