javascript - 以表格形式显示 Ajax 返回的数据
问题描述
我正在使用 Ajax+Jquery 从 PHP api 获取数据。在我做的最后一步的那个 PHP api 中-
$data_enc = json_encode($data); 回声 $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 端循环对象,但无法获得所需的结果。
解决方案
在您的 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 }))
)
}
}
})
推荐阅读
- javascript - 如何在Javascript中保持复选框的状态
- sql - SQL - 从连接两个表中获得结果的最快算法
- animation - FFmpeg:如何为每张视频幻灯片使用多个图像,并且动画/放大/缩小/淡化每个图像只有一个?
- ios - 如何执行 LinkingObject 的迁移?
- sublimetext3 - 如何在 Sublime Text 3d 中选择所选文本的上一个实例
- git - 如何从 Perforce 缓慢迁移到 Git
- php - 根据 Wordpress 用户对象中的数据创建带有指向页面的动态链接的按钮
- python - re.sub 具有相同字符串的不同答案跨行拆分
- intellij-idea - 无法将 PsiElement 转换为 KtClass - Intellij
- c# - 基于托管项目Targetframework的C#条件代码执行