Accessing JSON data in a Javascript variable
It's embarrassing to ask, but I freely admit that I'm a non-seasonal Javascript developer and I just can't figure it out. Hopefully this will just be dead to someone else, and I want to thank everyone here in advance for the help this site continually provides to me.
I asked this question a few days ago and I don't get this error anymore. But I ran into a wall trying to actually access the data stored in a variable. My JSON looks like this:
[
{"id":"1","name":"Bob","haircolor":"Brown"},
{"id":"2","name":"Carol","haircolor":"Red"}
]
It goes into a variable like:
var people=[];
$.getJSON("php/getpeople.php", function(data){ //getpeople.php generates the JSON
people.push(data);
});
By initializing people as an array, I don't get any more error messages. But I cannot access people's content. people.length
returns 0 and people[0]
u people[1]
is undefined.
It's there, I know it all, but I have the devil of a time figuring out where.
source to share
Try this: http://jsfiddle.net/hUq7k/
$.getJSON("php/getpeople.php", function(data){ //getpeople.php generates the JSON
$.each(data, function(i, people){
console.log(people.id); //<------this should output "1, 2"
});
});
make sure you get response data
.
source to share
The following should work if the server is actually returning the expected JSON:
$.getJSON("php/getpeople.php", function(data){ //getpeople.php generates the JSON
var people = data;
alert("people.length: " + people.length);
if (people.length > 0) {
alert("people[0].id: " + people[0].id);
}
});
The following shouldn't work i.e. people
will be undefined
because $ .getJSON is an asynchronous method and this code is trying to access people
before the AJAX operation completes.
var people;
$.getJSON("php/getpeople.php", function(data){ //getpeople.php generates the JSON
people = data;
});
alert("people.length: " + people.length);
if (people.length > 0) {
alert("people[0].id: " + people[0].id);
}
source to share