如何用jQuery/JavaScript解析JSON数据?我有一个Ajax调用,它返回一些JSON,如下所示:$(document).ready(function () {
$.ajax({
type: 'GET',
url: 'http://example/functions.php',
data: { get_param: 'value' },
success: function (data) {
var names = data
$('#cand').html(data);
}
});});内部#cand我去拿:[ { "id" : "1", "name" : "test1" },
{ "id" : "2", "name" : "test2" },
{ "id" : "3", "name" : "test3" },
{ "id" : "4", "name" : "test4" },
{ "id" : "5", "name" : "test5" } ]我如何循环这些数据并将每个名称放在div中?
3 回答
森林海
TA贡献2011条经验 获得超2个赞
dataType:'json'
$.ajax({ type: 'GET', url: 'http://example/functions.php', data: {get_param: 'value'}, dataType: 'json', success: function (data) { var names = data $('#cand').html(data); }});
parseJSON
:
var parsedJson = $.parseJSON(jsonToBeParsed);
var j ='[{"id":"1","name":"test1"},{"id":"2","name":"test2"},{"id":"3","name":"test3"},{"id":"4","name":"test4"},{"id":"5","name":"test5"}]';
$().each
:
var json = $.parseJSON(j);$(json).each(function (i, val) { $.each(val, function (k, v) { console.log(k + " : " + v); });});
ITMISS
TA贡献1871条经验 获得超8个赞
//start ajax request$.ajax({ url: "data.json", //force to handle it as text dataType: "text", success: function(data) { //data downloaded so we call parseJSON function //and pass downloaded data var json = $.parseJSON(data); //now json variable contains data in json format //let's display a few items for (var i=0;i<json.length;++i) { $('#results').append('<div class="name">'+json[i].name+'</>'); } }});
添加回答
举报
0/150
提交
取消