Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
148
rated 0 times [  150] [ 2]  / answers: 1 / hits: 37540  / 13 Years ago, wed, may 18, 2011, 12:00:00

I'm getting a JSON response from the server and i have to loop through the array in javascript and get the values. But I cant seem to loop throught it.



The JSON response of the array looks like this:



{
   1: Schools,
   20: Profiles,
   31: Statistics,
   44: Messages,
   50: Contacts
}


I just want to loop through it to get the ID and Name and populate some values on the page.



I have tried:



$.each(response, function(key, value) {
alert(key + ' ' + value);
});

// and

for (var key in response) {
alert(key + ' ' + response[key]);
}


But neither give the right values.



Thanks in advance for any help.



Reply:
Hi,
The response I'm getting with the second loop is:



0 {
1
2 1
3
4 :
5
6 S


etc etc



So that means its going through the whole response as a string and spliting it as key/value.



Thanks


More From » jquery

 Answers
12

Your problem is that you are not parsing the JSON string. Therefore, your foreach is going through the characters in the JSON string.



// If you are using jQuery.ajax, you can just set dataType to 'json' 
// and the following line will be done for you
var obj = jQuery.parseJSON( response );
// Now the two will work
$.each(obj, function(key, value) {
alert(key + ' ' + value);
});


for (var key in obj) {
alert(key + ' ' + response[key]);
}

[#92173] Tuesday, May 17, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
maryann

Total Points: 600
Total Questions: 104
Total Answers: 97

Location: Sint Maarten
Member since Tue, Mar 29, 2022
2 Years ago
;