"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Sequence Ajax Requests for Optimal Control?

How to Sequence Ajax Requests for Optimal Control?

Published on 2024-11-03
Browse:205

How to Sequence Ajax Requests for Optimal Control?

Sequencing Ajax Requests

When iterating through a collection and making individual Ajax calls for each element, it's essential to control the sequence to prevent server overload and browser freezing. While custom iterators can be employed, there are more elegant solutions available.

jQuery 1.5

In jQuery 1.5 and above, the $.ajaxQueue() plugin leverages $.Deferred, $.queue(), and $.ajax() to manage request sequencing and provide a promise that resolves upon request completion.

Implementation:

var jqXHR,
    dfd = $.Deferred(),
    promise = dfd.promise();

ajaxQueue.queue( doRequest );

promise.abort = function( statusText ) {
  if ( jqXHR ) {
    return jqXHR.abort( statusText );
  }
  var queue = ajaxQueue.queue(),
      index = $.inArray( doRequest, queue );
  if ( index > -1 ) {
    queue.splice( index, 1 );
  }
  dfd.rejectWith( ajaxOpts.context || ajaxOpts,
    [ promise, statusText, "" ] );
  return promise;
};

function doRequest( next ) {
  jqXHR = $.ajax( ajaxOpts )
    .done( dfd.resolve )
    .fail( dfd.reject )
    .then( next, next );
}

return promise;

};

})(jQuery);

jQuery 1.4

For jQuery 1.4, the animation queue can be utilized for creating a custom "queue." You can also create your own $.ajaxQueue() plugin that uses jQuery's 'fx' queue to automatically initiate the first request in the queue if it's not already running.

Implementation:

var oldComplete = ajaxOpts.complete;

ajaxQueue.queue(function(next) {
  ajaxOpts.complete = function() {
    if (oldComplete) oldComplete.apply(this, arguments);
    next();
  };
  $.ajax(ajaxOpts);
});

};

})(jQuery);

Example:

url: '/echo/html/',
data: {html : "[" idx "] " $(this).html()},
type: 'POST',
success: function(data) {
  $("#output").append($("<li>", { html: data }));
}

});
});

This ensures that each Ajax request is executed sequentially, allowing for graceful handling of server load and maintaining browser responsiveness.

Release Statement This article is reprinted at: 1729396281 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3