如何在javascript中循环JSON关联数组?
我从服务器获得JSON响应,我必须在javascript中循环遍历数组并获取值。但我似乎无法循环它。
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.
数组的JSON响应如下所示:
The JSON response of the array looks like this:
{
"1": "Schools",
"20": "Profiles",
"31": "Statistics",
"44": "Messages",
"50": "Contacts"
}
我只想循环遍历它以获取ID和名称并在页面上填充一些值。
I just want to loop through it to get the ID and Name and populate some values on the page.
我试过:
$.each(response, function(key, value) {
alert(key + ' ' + value);
});
// and
for (var key in response) {
alert(key + ' ' + response[key]);
}
但两者都没有给出正确的值。
But neither give the right values.
提前感谢您的帮助。
回复:
您好,
我在第二个循环中得到的回复是:
Reply: Hi, The response I'm getting with the second loop is:
0 {
1 "
2 1
3 "
4 :
5 "
6 S
等等
这意味着它将整个响应作为字符串并将其作为键/值分割。
So that means its going through the whole response as a string and spliting it as key/value.
谢谢
您的问题是您没有解析JSON字符串。因此,您的foreach将遍历JSON字符串中的字符。
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]);
}