在任何ajax回调中出现运行时错误后,ajaxStop事件停止激发



让我们看看我的代码:

$("#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事件成功触发。但是,如果您只按下一次"send-err"按钮,就会在ajax回调中引发运行时错误,那么以前的"send-ok"行为将永远不会再起作用——ajaxStop事件停止触发。

jQuery为什么这么做?除了到处使用try-catch之外,我还能做些什么来防止这种情况发生?

这就是我的工作原理:

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

最新更新