我有一个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中放置每个名字?
设置dataType:'json'将为您解析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);
});
});
JSFiddle
假设你的服务器端脚本没有设置正确的Content-Type: application/json响应头,你需要使用dataType: 'json'参数告诉jQuery这是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
}));
});
});
var jsonP = "person" : [ { "id" : "1", "name" : "test1" },
{ "id" : "2", "name" : "test2" },
{ "id" : "3", "name" : "test3" },
{ "id" : "4", "name" : "test4" },
{ "id" : "5", "name" : "test5" } ];
var cand = document.getElementById("cand");
var json_arr = [];
$.each(jsonP.person,function(key,value){
json_arr.push(key+' . '+value.name + '<br>');
cand.innerHTML = json_arr;
});
<div id="cand">
</div>