I have simple AJAX function that uses jQuery to return an array of 300 test objects from a database. I can see the data is returned, and I can use FireBug to step through the first loop and step into the constructor.
This data is copied to an JS array. The code fragment looks like:
//retrieve star locations to display on page
$.getJSON("stars.php?jsoncallback=?", function(data) {
for (var x=0, xx=data.length; x<xx; x++) {
// planetArray[x] = new Planet(data[x].xpos, data[x].ypos); // also doesn't work.
planetArray.push(new Planet(data[x].xpos, data[x].ypos));
}
});
for (var i=0, ii=planetArray.length; i<ii; i++) {
// display the data.
}
FireBug says planetArray.length
is zero. The Planet
constructor looks like:
function Planet(x, y) {
this.x = x;
this.y = y;
}
I think it is a scoping issue but I can't seem to figure it out. In other languages creating a new object means it exists on the heap and survives the scope, but here it seems to disappear into the ether.
How can I return an array and push it into my own array for use later (or even in another function)?