How to handle jQuery ajax post error when navigating away from a page

前端 未结 3 1978
天涯浪人
天涯浪人 2020-12-15 03:27

Is there a way to handle the error from an ajax request within JQuery such that when the user navigates away from the page, the resulting error is ignored?

$         


        
3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-15 04:15

    It looks like the answer to this is to examine the jqXHR.status. The XMLHttpRequest spec outlines these steps to set the status:

    The status attribute must return the result of running these steps:

    1. If the state is UNSENT or OPENED, return 0 and terminate these steps.

    2. If the error flag is set, return 0 and terminate these steps.

    3. Return the HTTP status code.1

    NOTE also: The error flag indicates some type of network error or request abortion. It is initially unset and is used during the DONE state.

    From what I understand therefore, this code check should fix the issue:

        if (xhr.status == 0)
            alert('error');
    

    1https://web.archive.org/web/20120204040047/http://www.w3.org/TR/XMLHttpRequest/#the-status-attribute

提交回复
热议问题