我有一个网络应用程序,它产生了大量$.post()请求.服务器必须按创建顺序接收这些内容.为了保证这一点,我首先想到我将自己的队列出队并在上一个Ajax调用完成之后触发了下一个Ajax调用
然后我看到有一个async:false选项,您可以使用$.ajax().
我已经更改了所有使用$.ajax({async:false,…})的请求,但是当我在Firebug中监视它们时,请求不会逐个发送,每个下一个请求都会在最后收到了回复.
什么是异步假设呢?我如何管理我的Ajax以便一次执行,下一个在最后一个完成时触发(收到响应)?
您可以创建一个从回调中递归调用的函数,而不是使用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 );
所以基本上:
>创建一个包含请求所需元素的对象数组.>创建一个接受数组的函数.>该函数从Array中删除第一项,并使用该对象填充请求属性.>在回调中,在调用该项的函数之后,对函数进行递归调用,传递Array的其余部分.>这将继续递归调用,直到Array为空.
