Make jQuery ajax calls in order -
i want make stack of ajax calls in way: call(n) starts after call(n-1) finished...
i cannot use async:false many reasons:
- some requests maybe jsonp (the relevant)
- i have other ajax requests may work meanwhile..
- the browser got blocked
i cannot chain requests way:
$.post('server.php', {param:'param1'}, function(data){ //process data $.post('server.php', {param:'param2'}, function(data){ //process data }); });
because number , params of requests dynamically created user input.
a small example illustrates problem.
you see server response order random, want achieve have in order
response arg1 response arg2 response arg3 response arg4 response arg5 response arg6
any appreciated, thanks.
ok, jquery ajax returns deferred object, can achieve this.
here how 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 '+args[index]), delay:delay}, function(data){ $('#response').append(data+'<br>'); }).then(function(){ deferredpost(index+1, max); }); } else { return $.post('/echo/html/', {html:('response '+args[index]), delay:delay}, function(data){ $('#response').append(data+'<br>'); }); } }
here used then function.
i recommend read little bit more deferred objects, can solve couple of common problems.
Comments
Post a Comment