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

前端 未结 3 1644
盖世英雄少女心
盖世英雄少女心 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:48

    The better way without timeouts and other magic flags is to check xhr headers. If no headers, then response didn't come from server, then request was aborted.

    var isUserAbortedRequest = function (xhr) {
        return !xhr.getAllResponseHeaders();
    }
    
    ajaxRequest
        .fail(function (xhr, error, statusText) {
            console.log("request aborted = ", isUserAbortedRequest(xhr));
        })
        .success(...)
    

    You can wrap your ajax request with $.Defered like below and use defered object's done\fail.

    $.Deferred(function (def) {           
        ajaxRequest
            .fail(function (xhr, error, statusText) {
                console.log("request aborted = ", isUserAbortedRequest(xhr));
    
                def.reject({ aborted: isUserAbortedRequest(xhr), error: error });
            })
            .success(function (response) {
                if (response.success == true) {
                    def.resolve(response.data);
                }
                else {
                    def.reject({ aborted: false, error: response.error });
                }
            });
    });
    
    0 讨论(0)
  • 2021-02-08 09:48
    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;});
    

    The above technique does not work for a periodically refreshing page (for example every half seconds). I have figured out that the error caused by refreshing the page can be avoided using delaying the error handling process by a small amount of time.

    Example:

    $.ajax(...)
    .success(...)
    .error(function(jqXHR) {
    setTimeout(function() {
      // error showing process
    }, 1000);
    });
    

    In addition to that

    window.onbeforeunload = function() {//stop ajax calls}

    event can be used for less frequently refreshing ajax calls.

    0 讨论(0)
  • 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;});
    
    0 讨论(0)
提交回复
热议问题