简体   繁体   中英

Multiple jquery ajax request - ways to handle it

If there is jquery ajax loading and I fire another ajax by quickly clicking the button, it kind of gets stuck. How can I handle multiple requests fired together?

How do I do following?

  1. Discard/abort all previous requests and only process the latest one.
  2. Do not allow new request until previous request completes (variation: can be same ajax request or any new ajax request from the page).

AJAX is Asynchronous. So you can fire them at the same time.

Or in the success callback (or .done() callback), you can call one request after another. So it will be easy to manage your issue (you click the button but get stucked), because you can control.

$.ajax({
  url: "http://..."
})
  .done(function( data ) {
    // Other AJAX call 
    // or restore disabled elements
    // while you were receiving the response.
  });

If you want a work-around, just tell me.

you can use ajax "beforeSend" to lock the current request.So that user can send a new request only if the previous one is done. As for the process sequence, you can use a global value to store data and always assign it with the new response value.

   function request(callback){
       if(!$btn.hasClass('disabled')){
           $.ajax({
               type:'...',
               url:'...',
               beforeSend:function(){
                  $btn.addClass('disabled');//so that user cannot send a new request
               },
               success:function(data){
                   window.g_data = data;
                   callback && callback()//success callback
                   $btn.removeClass('disabled');
               }
           })
       }


  }
  function callback(){

    //process window.g_data
  }

Have a look at this library:

Async is a utility module which provides straight-forward, powerful functions for working with asynchronous JavaScript.

Async

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM