使用jQuery进行同步Ajax请求

3

我有一个Web应用程序,它发送大量$.post()请求。服务器必须按创建的顺序接收这些请求。为了保证这一点,我首先想到制作自己的队列,在上一个Ajax调用完成后出列并触发下一个。

然后我看到在$.ajax()中有一个async:false选项。

我已经更改了所有的请求,使用$.ajax({ async: false, ... }),但是当我在Firebug中监视它们时,请求不是一个接一个地发送的,每个下一个请求都是在上一个请求接收到响应后才被触发的。

那么async到底意味着什么呢?如何处理我的Ajax使得每次只执行一个,下一个请求在上一个请求完成(收到响应)后再触发?

1个回答

7

不要使用async:false,你可以创建一个函数,从回调函数中递归调用它。

function sendReq( arr ) {
    var current = arr.shift(); // Remove the first item from the Array.
    $.ajax({
        url: current.url,      // Use the url from the first item.
        success: function( dat ) {
            current.func( dat );  // Call the function of the first item.
            if( arr.length )      // If there are items left in the Array,
               sendReq( arr );    //     make a recursive call, sending
        }                         //     the remainder of the array.
    });
}

// Ordered collection of requests to be made.
var req_set = [
    {url:'someurl', func:function( dat ) { /*do something with dat*/ }},
    {url:'anotherurl', func:function( dat ) { /*do something with dat*/ }},
    {url:'someother', func:function( dat ) { /*do something with dat*/ }}
];
 // Start the first call, sending the entire set.
sendReq( req_set );

简单来说:

  • 创建一个包含所需请求元素的对象数组。
  • 编写一个接受该数组的函数。
  • 该函数从数组中删除第一项,并使用该对象填充请求属性。
  • 在回调函数中,当该项的函数被调用后,对该函数进行递归调用,传递剩余的数组。
  • 这将继续递归调用,直到数组为空。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接