简体   繁体   English

有没有更好的方法来串行提交多个AJAX请求?

[英]Is there a better way to serially submit multiple AJAX requests?

I have a page with multiple forms that I submit via Ajax POSTs serially. 我有一个包含多个表单的页面,我通过串行方式通过Ajax POST提交。 At first, I tried using synchronous XHR requests, but this causes the browser to lock up for the duration of the request, and breaks my DOM-manipulation effects, which is unacceptable. 起初,我尝试使用同步XHR请求,但这会导致浏览器在请求期间锁定,并破坏我的DOM操作效果,这是不可接受的。 So the pattern I ended up using is basically this: 所以我最终使用的模式基本上是这样的:

var fcount = 0;    // incremented for each form to be submitted
function submit_form( num ) { 
    var fdata = { ... }; // data from form # num
    $.ajax( { async:    true,
              url:      '/index.cgi',
              data:     fdata,
              type:     'POST',
              success:  function() { 
                  if ( num < fcount ) { 
                      submit_form( ++num );
                  }
              }
           } );
}

$( '#submit_form_btn' ).click( function() { submit_form( 1 ) } );

The recursion strikes me as a bit of an ugly solution to what is essentially an iterative problem. 递归让我觉得这是一个基本上是迭代问题的丑陋解决方案。 Is there a cleaner or more elegant way that this could be handled? 是否有更清洁或更优雅的方式可以处理?

Are these requests idempotent? 这些请求是幂等的吗? If they are you can simply fire them off one after the other. 如果他们是你可以简单地一个接一个地解雇他们。 Otherwise you are somewhat limited by the asynchronous nature of AJAX. 否则你会受到AJAX异步性质的限制。

UPDATE UPDATE

I did some more research and apparently there exists a framework called jQuery Message Queuing that handles serial AJAX requests via message-queuing. 我做了一些研究,显然存在一个名为jQuery消息队列的框架,它通过消息队列来处理串行AJAX请求。 Maybe this can help you out. 也许这可以帮到你。

更简洁的方法是维护一个你想要制作的回调队列(ajax请求)并逐个解雇它们。

我会说在服务器上提高脚本的超时并在一个POST中发送所有内容。

If what you want to do is what your code does it is just fine to use a recursion structure. 如果您想要做的是您的代码所做的事情,那么使用递归结构就可以了。

But the suspicious part here is using more than one call, you are wasting a lot of time submitting multiple calls. 但是这里可疑的部分是使用多个电话,你浪费了很多时间提交多个电话。 Stick all the data in one call and get it over with, if it is in any way possible that is by far the preferred method. 将所有数据粘贴在一个调用中并将其结束,如果它是以任何可能的方式,这是目前为止的首选方法。

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

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