handle ajax error when a user clicks refresh

后端 未结 5 1171
忘掉有多难
忘掉有多难 2020-12-02 17:17

i apologise if this is something i should be able to look up. all of the terms i wanted were way overloaded..

here is my problem: when i open a page, it fires off a

5条回答
  •  时光取名叫无心
    2020-12-02 17:41

    There are several suggested approaches for detecting this:

    • Several have suggested the use of a beforeunload handler to set a boolean flag so that the error handler can know that the page is being unloaded (See list of related/duplicated posts below). This is great, except that mobile Safari on iOS doesn't support the beforeunload event.

    • Sachindra suggested an approach where instead of firing the error function immediately, it got delayed a second in a setTimeout(..., 1000). That way, there is a good chance the page has actually disappeared by the time the error handler gets called. "Good chance" that is. I bet if I have a huge page with e.g. many s, it could take more than 1 sec to unload, and then perhaps the error handler would fire anyway.

    I therefore suggest a combination of reliably detecting beforeunload support and if beforeunload is not supported (cough iPad/iPhone cough) revert to Sachindra's delay trick.

    See the full solution with beforeunload detection and all in this jsfiddle.

    It looks like the situation is a little better for jQuery 2.x than for 1.x, but 2.x also seems a little flakey, and so I still find this suggestion prudent.

    P.S: There were also suggestions involving testing some fields in the XHR / jqXHR object. (Here and here). I have not come accross a combination that could distinguish between user navigation and restarting the webserver during a long-running AJAX call, and I have therefore not found this approach useful to me.

    This is really also an answer to these related/duplicated Stack Overflow questions:

    • jQuery AJAX fires error callback on window unload?
    • $.ajax calls success handler when request fails because of browser reloading
    • How best to handle errors during jquery ajax calls caused by user clicking on links
    • Detecting that a jQuery.ajax call failed because the page is reloading?

    and these posts outside of Stack Overflow:

    • What's the proper way to deal with AJAX error because of page reload?
    • How to Distinguish a User-Aborted AJAX Call from an Error | I like stuff.

提交回复
热议问题