Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在jQuery中统一处理AJAX错误?_Javascript_Jquery_Ajax - Fatal编程技术网

Javascript 如何在jQuery中统一处理AJAX错误?

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

我想检测AJAX调用中的401个错误,并重定向到login.html。但我最终写了很多重复的代码,比如

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
 });