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

hus*_*007 5 javascript ajax jquery

让我们看看我的代码:

$("#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>");
});
Run Code Online (Sandbox Code Playgroud)

JSFiddle

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

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

小智 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    
});
Run Code Online (Sandbox Code Playgroud)