Ajax: How to prevent jQuery from calling the success event after executing xmlHttpRequest.abort();

后端 未结 6 1252
一个人的身影
一个人的身影 2020-12-31 16:34

Using jQuery\'s $.ajax() function. Wherether the request has been purposely aborted, or if the server is down (not responding) it appears the same outcome happens;

6条回答
  •  猫巷女王i
    2020-12-31 17:04

    The best solution to have only one request is assigning the return value of your $.ajax call to a variable, e.g. currentRequest, and then, inside your success(data, responseCode, xhr) function, checking if(xhr == currentRequest) and returning early if the check failed. When aborting you simply set currentRequest to null so the check fails.

    This ensures an old request is never handled which is especially important if you do e.g. long polling and restart the request as soon as it has finished (you really don't want two "pollers" running at the same time due to an aborted request starting a new one).

提交回复
热议问题