Skip to content Skip to sidebar Skip to footer

Accessing Json Data In A Javascript Variable

It's embarrassing to have to ask, but I freely admit I'm an unseasoned Javascript developer, and I just can't figure this out. Hopefully, this will be dead simple for someone else,

Solution 1:

people only gets values after the ajax event happens.

Call some callback function after you put the data into the people array.

Solution 2:

Try with 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 are getting the response data.

Solution 3:

The following should work, if the server is actually returning the expected JSON:

$.getJSON("php/getpeople.php", function(data){ //getpeople.php generates the JSONvar people = data;
    alert("people.length: " + people.length);
    if (people.length > 0) {
        alert("people[0].id: " + people[0].id);
    }
});

The following should not work, i.e., people will be undefined, because $.getJSON is an asynchronous method and this code is attempting to access people before the AJAX operation has completed.

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);
}

Post a Comment for "Accessing Json Data In A Javascript Variable"