请以jQuery的AJAX调用 [英] Make jQuery ajax calls in order
问题描述
我想打一摞阿贾克斯这样调用:调用(N)启动后调用(N-1)成品...
I want to make a stack of Ajax calls in this way: call(n) starts after call(n-1) finished...
我不能使用异步:假原因是多方面的:
I cannot use async:false for many reasons:
- 在一些要求可能的 JSONP 的(最相关)
- 在我有其他的Ajax请求,可能会同时工作..
- 在浏览器得到了阻止
- some requests maybe jsonp (the most relevant)
- I have other ajax requests that may work meanwhile..
- The browser got blocked
我不能链我的要求是这样的:
I cannot chain my requests this way:
$.post('server.php', {param:'param1'}, function(data){
//process data
$.post('server.php', {param:'param2'}, function(data){
//process data
});
});
由于该请求的数目,而params被动态地从用户输入创建
Because the number and params of the requests are dynamically created from user input.
一个小例如,说明我的问题。
A small example that illustrates my problem.
您会看到,服务器的响应顺序是随机的,我想要实现的是有它才能
You will see that the server response order is random, what I want to achieve is to have it in order
Response to arg1
Response to arg2
Response to arg3
Response to arg4
Response to arg5
Response to arg6
任何帮助将是非常pciated AP $ P $,表示感谢。
Any help would be very appreciated, thanks.
推荐答案
好了,jQuery的阿贾克斯返回href="http://api.jquery.com/category/deferred-object/" rel="nofollow">延迟的对象一个
Ok, jQuery Ajax returns a Deferred Object, this can help you achieve this.
下面是如何做到这一点:
Here is how to do it:
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>');
});
}
}
下面我用 ,然后 功能。
Here I used then function.
我还建议多读一点有关延迟对象,就可以解决几个常见的问题。
I also recommend to read a little bit more about deferred objects, they can solve a couple of common problems.
这篇关于请以jQuery的AJAX调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!