Abort JSONP ajax request with jQuery

前端 未结 5 1085
说谎
说谎 2020-12-28 19:36

I\'m using a JSONP ajax call to load some content from a different domain, and all this stuff is executed if the user causes a \"mouseover\" on a button.

I can captu

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-28 19:45

    Do not abort the request

    Just store somewhere the jqXHR object returned by $.ajax()

    theJqXHR = $.ajax(....
    

    If the user cancel the request null the saved object

    // user canceled
    theJqXHR = null;
    

    Finally when you receive the response (success callback) the callback will compare the jqXHR object of the response with the saved object.

    function successCallback(data, textStatus, jqXHR )
    {
        if( theJqXHR !== jqXHR )
        {
            // user canceled; discard the response
            return;
        }
    
        // process the response
    }
    

    No jQuery errors.


    As a general advice don't rely upon abort(), even for regular ajax requests.

    1. In any case you won't save resource on the server bacause the request you sent will be processed and there is no way to stop it. And a response will come back.

    2. Some (older) browsers handle abort() not properly.

    Just "cache" the jqXHR object and handle the CANCEL scenario yourself.

提交回复
热议问题