简体   繁体   English

多个jquery ajax请求-处理它的方法

[英]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. 如果有jquery ajax加载,而我通过快速单击该按钮来触发另一个ajax,则它会卡住。 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请求,也可以是页面中的任何新ajax请求)。

AJAX is Asynchronous. AJAX是异步的。 So you can fire them at the same time. 因此,您可以同时解雇他们。

Or in the success callback (or .done() callback), you can call one request after another. 或者在成功回调(或.done()回调)中,您可以一个接一个地调用一个请求。 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. 您可以使用ajax“ beforeSend”锁定当前请求。这样,只有在前一个请求完成后,用户才能发送新请求。 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. 异步是一个实用程序模块,它提供直接,强大的功能来处理异步JavaScript。

Async 异步

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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