Jquery Ajax 错误处理忽略中止 [英] Jquery Ajax error handling to ignore aborted

查看:40
本文介绍了Jquery Ajax 错误处理忽略中止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

我需要忽略aborted的错误.errorThrown 为空,textStatuserror.我如何检查aborted?

I need to ignore the error of aborted. errorThrown is null and textStatus is error. How do I check for aborted?

推荐答案

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

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.

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

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.

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

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.

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

这篇关于Jquery Ajax 错误处理忽略中止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆