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.pus开发者_StackOverflowh(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)?
The AJAX request happens asynchronously - you're not waiting for it to complete before you try and display the data.
Move the display code into the callback and it should work.
It should help if you add planetArray = [];
before the example code.
Actually just mergin both answers.
Like Greg said it works asynchronously meaning when second part (// display the data loop) is executed, the request didn't come back yet, so array is not filled.
var planetArray = [];
//retrieve star locations to display on page
$.getJSON("stars.php?jsoncallback=?", function(data) {
for (var x = 0; x < data.length; x++) {
planetArray.push(new Planet(data[x].xpos, data[x].ypos));
}
for (var i = 0; i < planetArray.length; i++) {
// exectutes after part below
// data already filled
}
});
for (var i = 0; i < planetArray.length; i++) {
// NO DATA YET
}
精彩评论