Is it possible to have a semi-async ajax call in jQuery?
I'm working on a site that involves looping through an array, using a jQuery ajax call for each element. Here is a simplified version:
var myArray=new Array("El1","El2","El3","El4");
for(var i=0; i<myArray.length; i++){
$.ajax({
开发者_JAVA百科 url: 'page.php?param='+myArray[i],
success: function(data){
//doing stuff with the data
//this needs to complete before the loop advances
}
});
}
I need each call to complete before advancing through the loop. I tried setting async:false
, which makes the loop work correctly, but that holds up the rest of the page's scripts and causes a lot of lagging. Is there some way that I can prevent the loop from advancing until the call is complete, but still be able to run other scripts asynchronously?
var idx = 0;
var urls = ["El1","El2","El3","El4"];
var doNextRequest = function() {
$.ajax({
url: 'page.php?param=' + urls[idx],
success: function(data) {
// ...
idx++;
if (idx < urls.length) {
doNextRequest();
}
}
});
}
doNextRequest();
There's no need for a loop if you make use of Array.shift
:
var myArray = new Array("El1", "El2", "El3", "El4");
function doRequest() {
if (!myArray.length) return;
var current = myArray.shift();
$.ajax({
url: 'page.php?param=' + current,
success: function(data) {
//doing stuff with the data
doRequest();
}
});
}
Call the next request in the success-handler of the previous. Something like this. (Could be a more elegant construct for this).
var myArray=new Array("El1","El2","El3","El4");
var i = 0;
function callAjax()
{
$.ajax({
url: 'page.php?param='+myArray[i],
success: function(data){
//doing stuff with the data
//this needs to complete before the loop advances
if (i < myArray.length)
{
i++;
callAjax();
}
}
});
}
精彩评论