June 22nd, 2010 posted by Bender Rodríguez
I needed to loop through an array, and then munge through a number of XML files, whose names were contained in said array, in order to build a series of lightbox gallaries for a low budget virtual tour of a college campus. Here's what I initially developed to bring together both the Lightbox/Thickbox framework and the simple gallery code:
var buildings = new Array("hedberg","lentz");
for (var x=0; x < buildings.length; x++) {
var myArray = [];
$.ajax({
type: "GET",
url: buildings[x] + ".xml",
dataType: "xml",
success: function(xml) {
var count = 0; //counter
$(xml).find('site').each(function() {
var url = $(this).find('url').text();
var target = $(this).find('target').text();w
var imageURL = $(this).find('imageURL').text();
var alt = $(this).find('alt').text();
myArray[parseInt(count)] =
new Array(imageURL, url, target, alt);
count++;
});
var gallery = new simpleGallery({
wrapperid: buildings[x],
dimensions: [523, 350],
imagearray: myArray,
autoplay: [true, 10000, 99],
persist: true,
fadeduration: 1000
})
}
});
}
Unfortunately, the for loop had moved on by the time the success function was called, so the value of "x" would be out of sync.
The solution? jQuery's ajax() API includes a flag for turning on and off the asyncronous function of the ajax call, which would suit me just fine since I did not need to have an asyncronous call. So you simply include:
async: false,
in your .ajax() call, and the for loop will not pass up your ajax calls. Good to go.
"You have to know how to accept rejection and reject acceptance."
Ray Bradbury