This is because of the "asynchronicity"...you will only have the correct
data length within the callback function from the getJSON call. Any code
along the same block as the getJSON call will be executed without regard to
the returned data.
What you can do is abstract the code where you are working with the
this.states array into a separate function, and then call this abstracted
function from the getJSON callback.
-- Josh
----- Original Message -----
From: "Mike Miller" <[EMAIL PROTECTED]>
To: "jQuery (English)" <jquery-en@googlegroups.com>
Sent: Monday, February 04, 2008 9:00 AM
Subject: [jQuery] Help populating an array via JSON
Hi,
I have a javascript function as follows:
function StateSuggestions() {
this.states =[];
$j.getJSON("client/ajax/getMedList.php", function(data){
alert("inside getJSON" + data.length);
this.states = data;
alert(this.states.length); //Value says 10
for (i = 0; i < data.length; i++) {
alert("test" + i);
}
});
alert(this.states.length); // Length here is 0
}
I want to populate the this.states array with data being retrieved by
the getJSON call...however it appears that the value of this.states is
different depending on whether or not you are inside the JSON call or
outside of it...not sure why...
M