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

2023-09-10 16:23:23 作者:懒床钉子户

我做很多$就来电了,我在抛出了一个消息的处理方式,从他们的错误。我觉得,如果一个Ajax调用正在进行,而页面被重新加载,如:点击刷新,或导航到另一个URL,然后我正在进行的ajax调用引发他们的错误回调。

我如何知道一个真正的错误之间的区别,以及调用中断,因为在页面重新加载得到?

  $。阿贾克斯(...)
。成功(...)
.error(函数(jqXHR){
  // jqXHR.status == 0方式,无论未能联系服务器,
  //或中止由于页面重载 - 我怎么能告诉区别?
});
 

解决方案

添加一个 卸载 处理程序,设置一个标志设置为true。然后,错误处理程序中,你可以检查此标志,并做适当的事情。

例如:

  VAR卸载= FALSE;
$阿贾克斯(...)...
 .error(函数(jqXHR){
    如果(卸载)回报; //忽略造成的导航离开错误
    //现在,检查是否有真正的错误..
});
$(窗口).unload(函数(){卸= TRUE;});
 

JQuery中ajax的相关方法总结

I do lots of $.ajax calls, and I handle errors from them in a way that throws up a message. I find that if an ajax call is in progress while the page gets reloaded, e.g. click refresh, or navigate to another URL, then my in-progress ajax calls trigger their error callbacks.

How can I tell the difference between a real error, and a call that aborted because the page got reloaded?

$.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?
});

解决方案

Add an unload handler, which sets a flag to true. Then, inside the error handler, you can check this flag, and do something appropriate.

Example:

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