如何在jquery中迭代json数据。
[{"id":"856","name":"India"},
{"id":"1035","name":"Chennai"},
{"id":"1048","name":"Delhi"},
{"id":"1113","name":"Lucknow"},
{"id":"1114","name":"Bangalore"},
{"id":"1115","name":"Ahmedabad"},
{"id":"1116","name":"Cochin"},
{"id":"1117","name":"London"},
{"id":"1118","name":"New York"},
{"id":"1119","name":"California"}
]
答案 0 :(得分:47)
您可以像这样使用$.each()
:
$.each(data, function(i, obj) {
//use obj.id and obj.name here, for example:
alert(obj.name);
});
答案 1 :(得分:6)
你也可以使用常规的javascript,我认为会更快一点(虽然我不确定jQuery如何优化each
):
var data = [{"id":"856","name":"India"},
{"id":"1035","name":"Chennai"},
{"id":"1048","name":"Delhi"},
{"id":"1113","name":"Lucknow"},
{"id":"1114","name":"Bangalore"},
{"id":"1115","name":"Ahmedabad"},
{"id":"1116","name":"Cochin"},
{"id":"1117","name":"London"},
{"id":"1118","name":"New York"},
{"id":"1119","name":"California"}
];
var data_length = data.length;
for (var i = 0; i < data_length; i++) {
alert(data[i]["id"] + " " + data[i]["name"]);
}
已编辑以反映尼克关于表现的建议
答案 2 :(得分:2)
您可以使用.each()
功能:
$(yourjsondata).each(function(index, element) {
alert('id: ' + element.id + ', name: ' + element.name);
});
答案 3 :(得分:2)
使用$ .each函数迭代所有对象的属性。在每次迭代中,您将获得名称/密钥和属性的值:
$.each(data, function(key, val) {
alert(key+ " *** " + val);
});