Jquery Ajax 错误处理忽略中止

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4807572/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:57:53  来源:igfitidea点击:

Jquery Ajax error handling to ignore aborted

jqueryajaxerror-handling

提问by Shawn Mclean

I want to have a global error handling method for ajax calls, this is what I have now:

我想有一个用于ajax调用的全局错误处理方法,这就是我现在所拥有的:

$.ajaxSetup({
  error: function (XMLHttpRequest, textStatus, errorThrown) {
    displayError();
  }
});

I need to ignore the error of aborted. errorThrownis null and textStatusis error. How do I check for aborted?

我需要忽略aborted. errorThrown为空且textStatuserror。我如何检查aborted

采纳答案by bluecollarcoder

I had to deal with the same use case today. The app I am working on has these long-running ajax calls that can be interrupted by 1) the user navigating away or 2) some kind of temporary connection/server failure. I want the error handler to run only for connection/server failure and not for the user navigating away.

我今天必须处理相同的用例。我正在开发的应用程序有这些长时间运行的 ajax 调用,这些调用可能会被 1) 用户导航或 2) 某种临时连接/服务器故障中断。我希望错误处理程序仅在连接/服务器故障时运行,而不是在用户离开时运行。

I first tried Alastair Pitts' answer, but it did not work because both aborted requests and connection failure set status code and readyState to 0. Next, I tried sieppl's answer; also did not work because in both cases, no response is given, thus no header.

我首先尝试了 Alastair Pitts 的回答,但它不起作用,因为中止请求和连接失败都将状态代码和 readyState 设置为 0。接下来,我尝试了 sieppl 的回答;也不起作用,因为在这两种情况下,都没有给出响应,因此没有标题。

The only solution that worked for me is to set a listener for window.onbeforeunload, which sets a global variable to indicate that the page has been unloaded. The error handler can then check and only call the error handler only if the page has not been unloaded.

唯一对我有用的解决方案是为 window.onbeforeunload 设置一个监听器,它设置一个全局变量来指示页面已被卸载。然后,错误处理程序可以检查并仅在页面尚未卸载时才调用错误处理程序。

var globalVars = {unloaded:false};
$(window).bind('beforeunload', function(){
    globalVars.unloaded = true;
});
...
$.ajax({
    error: function(jqXHR,status,error){
        if (globalVars.unloaded)
            return;
    }
});

回答by Udi

In modern jQuery you can just check if request.statusTextis equal to 'abort':

在现代 jQuery 中,您只需检查是否request.statusText等于'abort'

error: function (request, textStatus, errorThrown) {
    if (request.statusText =='abort') {
        return;
    }
}

回答by Alastair Pitts

Something I found is that when there is an aborted request, the statusand/or readyStateequal 0.

我发现,当请求中止时,status和/或readyState等于0.

In my global error handler, I have a check at the top of the method:

在我的全局错误处理程序中,我在方法的顶部有一个检查:

$(document).ajaxError(function (e, jqXHR, ajaxSettings, thrownError) {
    //If either of these are true, then it's not a true error and we don't care
    if (jqXHR.status === 0 || jqXHR.readyState === 0) {
        return;
    }

    //Do Stuff Here
});

I've found this works perfectly for me. Hope this helps you, or anyone else who runs into this :)

我发现这对我来说非常有效。希望这对您或其他遇到此问题的人有所帮助:)

回答by Paul Rademacher

You'll want to look at the textStatus argument passed into your error function. According to http://api.jquery.com/jQuery.ajax/, it can take the values "success", "notmodified", "error", "timeout", "abort", or "parsererror". "abort" is obviously what you want to check against.

您需要查看传递到错误函数中的 textStatus 参数。根据http://api.jquery.com/jQuery.ajax/,它可以取值“成功”、“未修改”、“错误”、“超时”、“中止”或“解析器错误”。“中止”显然是您要检查的对象。

Longer notes here: jquery-gotcha-error-callback-triggered-on-xhr-abort

这里有更长的注释:jquery-gotcha-error-callback-triggered-on-xhr-abort

回答by Sano J

Because bluecollarcoders answer doesn't work for ajax requests aborted by javascript, here is my solution:

因为 bluecollarcoders 的回答对 javascript 中止的 ajax 请求不起作用,这是我的解决方案:

var unloaded = false;
...
$(window).bind('beforeunload', function(){
    unloaded = true;
});


$(document).ajaxError(function(event, request, settings) {
    if (unloaded || request.statusText == "abort") {
        return;
    }
    ...
}

e.g.

例如

handler = jQuery.get("foo")
handler.abort()

will now be ignored by ajaxError handler

现在将被 ajaxError 处理程序忽略

回答by Leniel Maccaferri

Building upon Alastair Pitts'a answer, you can also do this to have more informative messages:

Alastair Pitts'a answer 的基础上,您也可以这样做以获得更多信息:

$(document).ajaxError(function (e, jqXHR, ajaxSettings, thrownError)
{
    {
        if (jqXHR.status === 0)
        {
            alert('Not connect.\n Verify Network.');
        } else if (jqXHR.status == 404)
        {
            alert('Requested page not found. [404]');
        } else if (jqXHR.status == 500)
        {
            alert('Internal Server Error [500].');
        } else if (exception === 'parsererror')
        {
            alert('Requested JSON parse failed.');
        } else if (exception === 'timeout')
        {
            alert('Time out error.');
        } else if (exception === 'abort')
        {
            alert('Ajax request aborted.');
        } else
        {
            alert('Uncaught Error.\n' + jqXHR.responseText);
        }
    }
});

回答by sieppl

$(document).ajaxError(function(event, jqXHR, ajaxSettings, thrownError) {

    if (!jqXHR.getAllResponseHeaders()) {
        return;
    }           
}); 

回答by Diego Malone

I had the same issue here, and what I did as solution was to set an "aborting" var just before the call of abort(), as below:

我在这里遇到了同样的问题,我作为解决方案所做的是在调用 abort() 之前设置一个“中止”变量,如下所示:

aborting = true;
myAjax.abort();

and only show the error on the error handler of the ajax request, if abort isn't true.

并且仅在 ajax 请求的错误处理程序上显示错误,如果 abort 不正确。

$.ajax({
    [..]
    error: function() {
        if ( !aborting ) {
            // do some stuff..
        }
        aborting = false;
    }
});

回答by Sky

If you abort the ajax request manually, you can do like this:

如果您手动中止 ajax 请求,您可以这样做:

var xhr;
function queryData () {
    if (xhr) {
      // tag it's been aborted
      xhr.hasAborted = true;

      // manually canceled request
      xhr.abort();
    }

    xhr = $.ajax({
        url: '...',
        error: function () {
            if (!xhr.hasAborted) {
                console.log('Internal Server Error!');
            }
        },
        complete: function () {
           xhr = null;
        }
    });
}