检测到jQuery.ajax调用失败,因为页面正在重新加载?

我做了很多$ .ajax调用,我以一种抛出消息的方式处理它们的错误。 我发现如果在重新加载页面时正在进行ajax调用,例如单击刷新,或导航到另一个URL,那么我正在进行的ajax调用会触发它们的错误回调。

如何判断真实错误和因重新加载页面而中止的调用之间的区别?

$.ajax(...) .success(...) .error(function(jqXHR) { // jqXHR.status == 0 means either failed to contact server, // or aborted due to page reload -- how can I tell the difference? }); 

添加unload处理程序,将标志设置为true。 然后,在error处理程序中,您可以检查此标志,并执行适当的操作。

例:

 var unloading = false; $.ajax(...) ... .error(function(jqXHR) { if (unloading) return; // Ignore errors caused by navigating away // Now, check for real errors .. }); $(window).unload(function() {unloading = true;}); 

没有超时和其他魔术标志的更好方法是检查xhr标头。 如果没有标题,则响应不是来自服务器,则请求被中止。

 var isUserAbortedRequest = function (xhr) { return !xhr.getAllResponseHeaders(); } ajaxRequest .fail(function (xhr, error, statusText) { console.log("request aborted = ", isUserAbortedRequest(xhr)); }) .success(...) 

您可以使用$ .Defered包装您的ajax请求,如下所示,并使用deferred对象的done \ fail。

 $.Deferred(function (def) { ajaxRequest .fail(function (xhr, error, statusText) { console.log("request aborted = ", isUserAbortedRequest(xhr)); def.reject({ aborted: isUserAbortedRequest(xhr), error: error }); }) .success(function (response) { if (response.success == true) { def.resolve(response.data); } else { def.reject({ aborted: false, error: response.error }); } }); }); 
 var unloading = false; $.ajax(...) ... .error(function(jqXHR) { if (unloading) return; // Ignore errors caused by navigating away // Now, check for real errors .. }); $(window).unload(function() {unloading = true;}); 

上述技术不适用于定期刷新页面(例如每半秒)。 我已经发现,使用延迟error handling过程少量时间可以避免刷新页面引起的错误。

例:

 $.ajax(...) .success(...) .error(function(jqXHR) { setTimeout(function() { // error showing process }, 1000); }); 

在此之上

window.onbeforeunload = function(){//停止ajax调用}

事件可用于较少刷新ajax调用。