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

后端 未结 6 1224
一个人的身影
一个人的身影 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条回答
  •  死守一世寂寞
    2020-12-31 17:06

    jQuery < 1.5

    For jQuery < 1.5 I have come up with the following solution:

    var request = $.ajax( /* ... */ );
    
    // ...
    
    request.onreadystatechange = function () {};
    request.abort();
    

    So, basically what I do, is to remove the success callback handler before calling abort().

    This works like a charm.

    jQuery >= 1.5:

    Starting with jQuery 1.5 the $.ajax(), $.get(), … functions return the jXHR object (api documentation) instead of the xmlHttpRequest object. Hence you can not simply overwrite the xmlHttpRequest.onreadystatechange() handler.

    This said, the jXHR.abort() takes care of not calling the success callback handler. Hence it is sufficient to call jXHR.abort().

    You do necessarily not need to update your previous code, as setting an onreadystatechange to jXHR will just have no effect at all.

    Long story short, startin with jQuery 1.5, this will do:

    var jxhr = $.ajax( /* ... */ );
    
    // ...
    
    jxhr.abort();
    

提交回复
热议问题