How to cancel/abort jQuery AJAX request?

后端 未结 8 2024
时光说笑
时光说笑 2020-11-22 09:30

I\'ve an AJAX request which will be made every 5 seconds. But the problem is before the AJAX request if the previous request is not completed I\'ve to abort that request and

相关标签:
8条回答
  • 2020-11-22 10:06

    I know this might be a little late but i experience similar issues where calling the abort method didnt really aborted the request. instead the browser was still waiting for a response that it never uses. this code resolved that issue.

     try {
            xhr.onreadystatechange = null;
            xhr.abort();
    } catch (e) {}
    
    0 讨论(0)
  • 2020-11-22 10:10

    Create a function to call your API. Within this function we define request callApiRequest = $.get(... - even though this is a definition of a variable, the request is called immediately, but now we have the request defined as a variable. Before the request is called, we check if our variable is defined typeof(callApiRequest) != 'undefined' and also if it is pending suggestCategoryRequest.state() == 'pending' - if both are true, we .abort() the request which will prevent the success callback from running.

    // We need to wrap the call in a function
    callApi = function () {
    
        //check if request is defined, and status pending
        if (typeof(callApiRequest) != 'undefined'
            && suggestCategoryRequest.state() == 'pending') {
    
            //abort request
            callApiRequest.abort()
    
        }
    
        //define and make request
        callApiRequest = $.get("https://example.com", function (data) {
    
            data = JSON.parse(data); //optional (for JSON data format)
            //success callback
    
        });
    }
    

    Your server/API might not support aborting the request (what if API executed some code already?), but the javascript callback will not fire. This is useful, when for example you are providing input suggestions to a user, such as hashtags input.

    You can further extend this function by adding definition of error callback - what should happen if request was aborted.

    Common use-case for this snippet would be a text input that fires on keypress event. You can use a timeout, to prevent sending (some of) requests that you will have to cancel .abort().

    0 讨论(0)
  • 2020-11-22 10:19

    The jquery ajax method returns a XMLHttpRequest object. You can use this object to cancel the request.

    The XMLHttpRequest has a abort method, which cancels the request, but if the request has already been sent to the server then the server will process the request even if we abort the request but the client will not wait for/handle the response.

    The xhr object also contains a readyState which contains the state of the request(UNSENT-0, OPENED-1, HEADERS_RECEIVED-2, LOADING-3 and DONE-4). we can use this to check whether the previous request was completed.

    $(document).ready(
        var xhr;
    
        var fn = function(){
            if(xhr && xhr.readyState != 4){
                xhr.abort();
            }
            xhr = $.ajax({
                url: 'ajax/progress.ftl',
                success: function(data) {
                    //do something
                }
            });
        };
    
        var interval = setInterval(fn, 500);
    );
    
    0 讨论(0)
  • 2020-11-22 10:25

    When you make a request to a server, have it check to see if a progress is not null (or fetching that data) first. If it is fetching data, abort the previous request and initiate the new one.

    var progress = null
    
    function fn () {    
        if (progress) {
            progress.abort();
        }
        progress = $.ajax('ajax/progress.ftl', {
            success: function(data) {
                //do something
                progress = null;
            }
        });
    }
    
    0 讨论(0)
  • 2020-11-22 10:25

    Why should you abort the request?

    If each request takes more than five seconds, what will happen?

    You shouldn't abort the request if the parameter passing with the request is not changing. eg:- the request is for retrieving the notification data. In such situations, The nice approach is that set a new request only after completing the previous Ajax request.

    $(document).ready(
    
        var fn = function(){
    
            $.ajax({
                url: 'ajax/progress.ftl',
                success: function(data) {
                    //do something
                },
    
                complete: function(){setTimeout(fn, 500);}
            });
        };
    
         var interval = setTimeout(fn, 500);
    
    );
    
    0 讨论(0)
  • 2020-11-22 10:25

    jQuery: Use this as a starting point - as inspiration. I solved it like this: (this is not a perfect solution, it just aborts the last instance and is WIP code)

    var singleAjax = function singleAjax_constructor(url, params) {
        // remember last jQuery's get request
        if (this.lastInstance) {
            this.lastInstance.abort();  // triggers .always() and .fail()
            this.lastInstance = false;
        }
    
        // how to use Deferred : http://api.jquery.com/category/deferred-object/
        var $def = new $.Deferred();
    
        // pass the deferrer's request handlers into the get response handlers
        this.lastInstance = $.get(url, params)
            .fail($def.reject)         // triggers .always() and .fail()
            .success($def.resolve);    // triggers .always() and .done()
    
        // return the deferrer's "control object", the promise object
        return $def.promise();
    }
    
    
    // initiate first call
    singleAjax('/ajax.php', {a: 1, b: 2})
        .always(function(a,b,c) {console && console.log(a,b,c);});
    
    // second call kills first one
    singleAjax('/ajax.php', {a: 1, b: 2})
        .always(function(a,b,c) {console && console.log(a,b,c);});
        // here you might use .always() .fail() .success() etc.
    
    0 讨论(0)
提交回复
热议问题