我正在使用Ajax + Jquery从PHP api获取数据。在最后一步中的那个PHP API中,我这样做了-
$ data_enc = json_encode($ data); echo $ data_enc;
我得到这个退货-
{"headers":["Age","Count","Consent","Intent"],"data":{"17":{"Age":"17","Count":2,"Consent":"2","Intent":0},"18":{"Age":"108","Count":3,"Consent":"3","Intent":0},"115":{"Age":"115","Count":1,"Consent":"1","Intent":0},"117":{"Age":"117","Count":2,"Consent":"2","Intent":0},"118":{"Age":"118","Count":1,"Consent":"1","Intent":0},"Totals":{"Age":"Total","Count":67,"Consent":67,"Intent":0}}}
在Jquery方面,
success: function(data){
alert(typeof(data)); //returns string
},
当我在jQuery Ajax成功中执行typeof(data)时,它说它是一个字符串。 我需要在具有年龄,计数,同意,目的列的表中显示此数据。
我尝试在jQuery端遍历对象,但无法获得所需的结果。
答案 0 :(得分:1)
在您的Ajax请求中使用dataType:'json'。
要建立表格:
HTML:
<table id="myTable">
<thead></thead>
<tbody></tbody>
</table>
JS:
$.ajax({
url: '...',
dataType: 'json',
success: function (result) {
$('#myTable tr').empty();
var header = $('#myTable thead');
var body = $('#myTable tbody');
var hTr;
$('#myTable thead').append(hTr = $('<tr>'));
// Headers
for (var h = 0; h < result.headers.length; h++) {
hTr.append($('<th>', { text: result.headers[h] }))
}
// Body
for (var d in result.data) {
var data = result.data[d];
$('#myTable tbody').append($('<tr>')
.append($('<td>', { text: data.Age }))
.append($('<td>', { text: data.Count }))
.append($('<td>', { text: data.Consent }))
.append($('<td>', { text: data.Intent }))
)
}
}
})