Detecting that a jQuery.ajax call failed because the page is reloading?

前端 未结 3 1646
盖世英雄少女心
盖世英雄少女心 2021-02-08 09:23

I do lots of $.ajax calls, and I handle errors from them in a way that throws up a message. I find that if an ajax call is in progress while the page gets reloaded, e.g. click

3条回答
  •  攒了一身酷
    2021-02-08 09:52

    Add an unload handler, which sets a flag to true. Then, inside the error handler, you can check this flag, and do something appropriate.

    Example:

    var unloading = false;
    $.ajax(...) ...
     .error(function(jqXHR) {
        if (unloading) return; // Ignore errors caused by navigating away
        // Now, check for real errors ..
    });
    $(window).unload(function() {unloading = true;});
    

提交回复
热议问题