ajaxStop事件在任何ajax回调中的运行时错误后停止触发

时间:2014-08-27 08:23:45

标签: javascript jquery ajax

让我们看看我的代码:

$("#senderr").on("click", function(){
   $.get("/echo/json").then(function(res){
      //let's imagine something happen
      throw "error";
   });
});

$("#sendok").on("click", function(){
    $.get("/echo/json").then(function(res){
        $("#log").append("<li>send ok</li>");
    });
});

$(document).on("ajaxStart", function(){
    $("#log").append("<li>start</li>");
});

$(document).on("ajaxStop", function(){
    $("#log").append("<li>stop</li>");
});

JSFiddle

如果按“发送确定”,则可以看到ajaxStart和ajaxStop事件已成功触发。但是,如果您只是按下“发送错误”按钮,这会在ajax回调中抛出运行时错误,之前的“发送确定”行为将永远不会再次起作用 - ajaxStop事件将停止触发。

为什么jQuery会这样做?除了在任何地方使用try-catch之外,我该怎么做才能防止这种情况发生?

2 个答案:

答案 0 :(得分:4)

这对我有用:

jQuery(window).on('error', function (e) {    
    // This tells jQuery no more ajax Requests are active
    // (this way Global start/stop is triggered again on next Request)
    jQuery.active--;
    //Do something to handle the error    
});

答案 1 :(得分:-1)

我在datatables jquery中遇到错误。  “无法读取属性'insertBefore'的null”

错误发生后,未触发ajaxStop事件。 上述解决方案对我也有用

jQuery(window).on('error', function (e) {
    // This tells jQuery no more ajax Requests are active
    // (this way Global start/stop is triggered again on next Request)
    jQuery.active = 0;
    //Do something to handle the error
});

由于

相关问题