我有一个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 div里面我会得到:
[ { "id" : "1","name" : "test1" },{ "id" : "2","name" : "test2" },{ "id" : "3","name" : "test3" },{ "id" : "4","name" : "test4" },{ "id" : "5","name" : "test5" } ]
如何遍历此数据并将每个名称放在div中?
解决方法
假设您的服务器端脚本未设置正确的Content-Type:application / json响应头,您需要使用dataType:’json’参数向jQuery指示这是JSON。
然后你可以使用$.each()函数循环遍历数据:
$.ajax({
type: 'GET',dataType: 'json',success: function (data) {
$.each(data,function(index,element) {
$('body').append($('<div>',{
text: element.name
}));
});
}
});
或使用$ .getJSON方法:
$.getJSON('/functions.PHP',{ get_param: 'value' },function(data) {
$.each(data,element) {
$('body').append($('<div>',{
text: element.name
}));
});
});