我希望以这种方式进行一堆Ajax调用:call(n)在调用(n-1)完成后启动...
我不能使用async:false有很多原因:
我不能这样链接我的请求:
$.post('server.php', {param:'param1'}, function(data){
//process data
$.post('server.php', {param:'param2'}, function(data){
//process data
});
});
Run Code Online (Sandbox Code Playgroud)
因为请求的数量和参数是从用户输入动态创建的.
一个小例子说明了我的问题.
您将看到服务器响应顺序是随机的,我想要实现的是按顺序排列
Response to arg1
Response to arg2
Response to arg3
Response to arg4
Response to arg5
Response to arg6
Run Code Online (Sandbox Code Playgroud)
任何帮助将非常感谢,谢谢.
好的,jQuery Ajax返回一个Deferred Object,这可以帮助你实现这一目标.
这是怎么做的:
var args = ['arg1','arg2','arg3','arg4','arg5','arg6'];
deferredPost(0, 5);
function deferredPost(index, max){
var delay = Math.random()*3;
if (index<max){
return $.post('/echo/html/', {html:('Response to '+args[index]), delay:delay},
function(data){
$('#response').append(data+'<br>');
}).then(function(){
deferredPost(index+1, max);
});
} else {
return $.post('/echo/html/', {html:('Response to '+args[index]), delay:delay},
function(data){
$('#response').append(data+'<br>');
});
}
}
Run Code Online (Sandbox Code Playgroud)
在这里,我用那么函数.
我还建议您阅读更多有关延迟对象的内容,它们可以解决一些常见问题.
| 归档时间: |
|
| 查看次数: |
7149 次 |
| 最近记录: |