ajax1 :function(a){ /** * 参数 a = {} * a.data {} * a.url str * a.type str * a.succ function * a.error function * a.loading function * a.complete function * a.timeout str || 8S */ a = a||{}; a.url = baseUrl + "/" + (a.url||''); a.data = a.data||{}; a.type = a.type||'GET'; a.timeout = a.timeout||60000; a.useWaiting = a.useWaiting || false; if(!a.url){return;} if(window.XMLHttpRequest){ var oA = new XMLHttpRequest(); }else{ var oA = new ActiveXObject('Microsoft.XMLHTTP'); } switch(a.type.toLowerCase()){ case 'get': oA.open('GET',a.url + '?' + strToUrl(a.data),true); oA.setRequestHeader('site','pc'); oA.send(); break; case 'post': oA.open('POST',a.url,true); oA.setRequestHeader('Content-Type','application/json; charset=utf-8'); oA.setRequestHeader('site','pc'); oA.send(strToUrl(a.data)); break; case 'post-json': oA.open('POST',a.url,true); oA.setRequestHeader('Content-Type','application/json; charset=utf-8'); oA.setRequestHeader('site','pc'); oA.send(a.data); break; case 'post-url': oA.open('POST',a.url + '?' + strToUrl(a.data),true); oA.setRequestHeader('Content-Type','application/json; charset=utf-8'); oA.setRequestHeader('site','pc'); oA.send(); break; } if(a.useWaiting){ layer.load(0, {shade: "#fff"}); } clearTimeout(timer); var timer = setTimeout(function(){ a.complete&&a.complete(); a.error&&a.error('系统繁忙,请稍后重试'); oA.onreadystatechange = null; },a.timeout);
oA.onreadystatechange = function(){
layer.closeAll('loading');
if(oA.readyState == 4){
if(oA.status>=200&&oA.status<300||oA.status==304){
clearTimeout(timer);
a.complete&&a.complete();
try {
let r= oA.responseText;
var code= JSON.parse(r).code;
if(code == 200){
a.succ&&a.succ(JSON.parse(r).data);
}else if(code==804){
sessionStorage.clear();
var loginBefore=decodeURIComponent((new RegExp('[?|&]logBefore='+'([^&;]+?)(&|#|;|$)').exec(location.href)||[,""])[1].replace(/\+/g,'%20'))||null;
if(loginBefore==null || loginBefore==""){
if(document.location.href.split("#").length>1){
window.location.href=login+"?logBefore="+encodeURI(document.location.href.split("#")[1]);
}else{
window.location.href=login;
}
}else{
window.location.href=login+"?logBefore="+loginBefore;
}
}else{
//layer.alert(JSON.parse(r).msg || "网络异常")
var errorMsg = JSON.parse(r).msg || "系统繁忙,请稍后重试";
layer.msg(errorMsg, {time: 2000});
if(a.imgCodeError){
a.imgCodeError&&a.imgCodeError();
}
}
} catch (error) {
console.log(error);
}
}else{
clearTimeout(timer);
layer.msg('系统繁忙,请稍后重试', {time: 2000});
}
}
};
// ==== data->URL ====
function strToUrl(b){
b.t = Math.random();
var arr = [];
for(var name in b){
arr.push(name + '=' + encodeURIComponent(b[name]));
}
return arr.join('&');
}
}
原生的ajax代码如上,试了各种方法依然解决不了复制代码