Change page in the middle of Ajax request

前端 未结 5 612
面向向阳花
面向向阳花 2021-01-17 12:07

What happens if I send some ajax request, and immediately change the page (say follow some link) before the request returns? I mean I suppose the XHR object sends a request

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-17 12:22

    The trick is to check the response headers in the XMLHttpRequest object. If there are no response headers (null or empty string, depending on the browser), the server did not respond yet. That means the user aborted.

    $.ajax({
        url: "url-to-go-here",
        success: function() {
        },
        error: function(xhr, textStatus, errorThrown) {
            if(!isUserAborted(xhr)) {
                console.log("Ajax Error")
            }
        }
    });
    
    function isUserAborted(xhr) {
      return !xhr.getAllResponseHeaders();
    }
    

    Source

提交回复
热议问题