我有一个网络应用程序,提出了大量的$.post()请求.服务器必须按创建顺序接收这些内容.为了保证这一点,我首先想到我将自己的队列出队并在上一个Ajax调用完成之后触发了下一个Ajax调用.
然后我看到async:false你可以使用的选项$.ajax().
我已经更改了我要使用的所有请求$.ajax({ async: false, ... }),但是当我在Firebug中监视它们时,请求不会逐个发送,每个下一个请求在最后一个请求被收到响应后被触发.
那么async假设要做什么?我如何管理我的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 );
Run Code Online (Sandbox Code Playgroud)
所以基本上: