我有一个 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
响应 header ,您需要使用 dataType: ' 向 jQuery 指示这是 JSON json'
参数。
那么您可以使用 $.each()
循环数据的函数:
$.ajax({
type: 'GET',
url: 'http://example/functions.php',
data: { get_param: 'value' },
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, function(index, element) {
$('body').append($('<div>', {
text: element.name
}));
});
});
https://stackoverflow.com/questions/8951810/