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

时间:2022-11-29 13:39:51

Lets look a code:

让我们看一下代码:

$("#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>");
});

http://jsfiddle.net/huston007/mBBJM/4749/

http://jsfiddle.net/hus​​ton007/mBBJM/4749/

If you press "send ok", you can see that ajaxStart and ajaxStop events fired successfully. But if you just once press "send err" button which thrown runtime error in ajax callback, previous "send ok" behavior will never work again - ajaxStop event stop firing.

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

Why jQuery do it? What can i do to prevent this except using try-catch everywhere?

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

2 个解决方案

#1


4  

That's what worked for me:

这对我有用:

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

#2


-1  

I was getting an error in datatables jquery . "Cannot read property 'insertBefore' of null"

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

After the error, the ajaxStop event was not triggered. The above solution also worked for me

发生错误后,未触发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
});

Thanks

谢谢

#1


4  

That's what worked for me:

这对我有用:

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

#2


-1  

I was getting an error in datatables jquery . "Cannot read property 'insertBefore' of null"

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

After the error, the ajaxStop event was not triggered. The above solution also worked for me

发生错误后,未触发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
});

Thanks

谢谢