如何从一个页面导航离开时,处理jQuery的AJAX的POST错误错误、页面、AJAX、jQuery

2023-09-11 00:48:41 作者:不已猥琐惊天下

有没有办法从内部JQuery的Ajax请求处理的错误,例如,当用户从页面导航离开,由此产生的误差被忽略?

Is there a way to handle the error from an ajax request within JQuery such that when the user navigates away from the page, the resulting error is ignored?

$(document).ready(function() {
 $.ajax( {
    url:'/server/url/',
    type: 'POST',
    data: {some..data},
    success:function(response) { do stuff with response },
    error: function(xhr, textStatus, errorThrown) {
           // Don't raise this alert if user has navigated away from the page
           alert('error');
    }
});

我很好奇,如果有人知道的一个干净的方式来处理呢?我知道你可以创建一个 $(窗口)一些逻辑.bind(beforeunload功能(){})方法,但我想preFER如果有是一种方式,因为Chrome浏览器似乎不再支持它处理的情况没有这样做。有例如在这种情况下,返回的一个特定的错误?

I'm curious if anybody knows of a clean way to handle this? I know you could create some logic in a $(window).bind("beforeunload", function(){}) method but I'd prefer if there was a way to handle the situation without doing this since Chrome appears to no longer support it. Is there for example a specific error that is returned in this case?

感谢。

推荐答案

它看起来像这个问题的答案是检查jqXHR.status。该 XMLHtt prequest规范概述了这些步骤设置状态:

It looks like the answer to this is to examine the jqXHR.status. The XMLHttpRequest spec outlines these steps to set the status:

状态属性必须返回运行这些步骤的结果是:

The status attribute must return the result of running these steps:

如果状态未发送或打开,返回0,并终止这些步骤。

If the state is UNSENT or OPENED, return 0 and terminate these steps.

如果错误标志设置,返回0,并终止这些步骤。

If the error flag is set, return 0 and terminate these steps.

返回HTTP状态code。

Return the HTTP status code.

还要注意: 错误标志表示某种类型的网络错误或要求流产。它最初是取消设置,并在完成状态被使用。

NOTE also: The error flag indicates some type of network error or request abortion. It is initially unset and is used during the DONE state.

从我因此明白了,这code检应该可以解决这个问题:

From what I understand therefore, this code check should fix the issue:

    if (xhr.status == 0)
        alert('error');