Multiple ajax call processing

I use jQuery to create some ajax calls and wonder how people deal with this situation.

  • To get some information, the server requests an ajax request.
  • Before the request, another request is returned. The first request is now invalid and expired.

How can I say that the original request is now invalid and can be ignored when it is returned. I only want to display the results of the second query and ignore (or cancel) the first.

+3
source share
5 answers

jQuery returns the object XmlHttpRequestfrom the call ajax()that I used to achieve the desired:

var lastRequest;
function getSomeData() {
    if(lastRequest) {
        lastRequest.abort();
        lastRequest = null
    }
    lastRequest = $.ajax(...);
}

, , .

+13

(: "request_id" ), . 1 . , request_id, , , .

+2

, , , . , , , , .

var incrementor = 1;
var lastSent = 0;

jQuery(document).ready(function() {

    jQuery('a.submitter').click(function(event) {
        event.preventDefault();
        lastSent = incrementor;
        incrementor++;
        jQuery.post(
            'some-url.php',
            {
                'request-id': lastSent,
                'other-data': 'some-data'
            },
            function( data, textStatus ) {
                if( data.requestId == lastSent ) {
                    // Do stuff
                }
            },
            'json'
        );
    });

});
0

, . -

$(function() {
    $('.ajaxButton').click(function() {
        $.currentCallId = (new Date()).getTime();

        $.ajax({
            type: "get",
            url: 'http://www.google.com/',
            beforeSend: function(xhr) {
                this.callId = $.currentCallId;
            },
            success: function(data) {
                if (this.callId === $.currentCallId) {
                    // process it
                } else {
                    // throw it out
                }
            }
        });
    });
});
-1

Source: https://habr.com/ru/post/1702850/


All Articles