Javascript 如何在jQuery中统一处理AJAX错误?
我想检测AJAX调用中的401个错误,并重定向到login.html。但我最终写了很多重复的代码,比如Javascript 如何在jQuery中统一处理AJAX错误?,javascript,jquery,ajax,Javascript,Jquery,Ajax,我想检测AJAX调用中的401个错误,并重定向到login.html。但我最终写了很多重复的代码,比如 if (xhr.status === 401) { location.assign('/login.html'); } 在错误回调中 我的问题是,有没有一种方法(最好的方法?)来统一处理它们?我可以在所有这些Ajax调用中插入一些代码吗?您可以使用ajaxError()来实现这一点。当ajax完成但出现错误时,将触发此事件。然后你可以像这样检查状态 $(document).ajaxEr
if (xhr.status === 401) {
location.assign('/login.html');
}
在错误
回调中
我的问题是,有没有一种方法(最好的方法?)来统一处理它们?我可以在所有这些Ajax调用中插入一些代码吗?您可以使用
ajaxError()
来实现这一点。当ajax完成但出现错误时,将触发此事件。然后你可以像这样检查状态
$(document).ajaxError(function (event, jqxhr, settings, exception) {
if (jqxhr.status == 401) {
location.assign('/login.html');
}
});
function myAJax(sURL,fnSuccess,fnError) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4) {
if(xhttp.status == 200){
fnSuccess(xhttp.responseText);
}else{
fnError('Http Error',xhttp)
}
}
}
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
myAJax('server/url',function(data){
//success code here
},function(){
//error code here
});