javascript - 从 json 对象动态构造一个有序的 html 表
问题描述
ajax 响应正在返回 json 对象,我想从中构造一个表。json 包含数组中的列标题和另一个字典数组中的实际数据。我希望根据标题数组对表列进行排序:
{
"columns": ["id", "category"],
"data":[
{"category": "fruit","id": 1},
{"category": "diary","id": 2}
]
}
$(document).ready(function() {
$("#submit").click(function(event) {
$.ajax({
data: {
user: $('#user').val(),
},
type: 'POST',
dataType: "json",
url: '/process'
})
.done(function(response) {
if (response.error) {
alert('Error!');
}
else {
var html = '<table class="table table-bordered"><thead><tr>';
jQuery.each(response.columns, function(index, value) {
html += "<th>" + value + "</th>"
})
html += "</tr></thead><tbody><tr>"
jQuery.each(response.data, function(index, value) {
jQuery.each(response.columns, function(idx, col) {
html+="<td>" + value[col] + "</td>"
})
})
html+="</tr></tbody></table>"
$(resulttable).append(html);
}
});
event.preventDefault();
});
});
我得到一张这样的桌子:
id category
1 fruit 2 diary
instead of
id category
1 fruit
2 diary
解决方案
您需要为每个数据行创建一个新的表格行。
html += "</tr></thead><tbody>"
jQuery.each(response.data, function(index, value) {
html += "<tr>"; //new code
jQuery.each(response.columns, function(idx, col) {
html+="<td>" + value[col] + "</td>"
})
html += "</tr>"; //new code
})
html += "</tbody></table>"
推荐阅读
- vim - 为什么这个 vim 函数不能工作,而是作为 cmd 运行
- python - 如何迭代 4 x 4 NumPy 矩阵类?
- python - 熊猫合并问题
- angular - 设置 mat-datepicker 的范围
- python - 使用 python docx 突出显示 word doc 中的所有日期值
- laravel - 在 Laravel 中包含 dataTables.css 时遇到问题
- c - C 编程 - 指针地址字节拆分
- vba - 在运行代码之前检查不同的范围
- json - 在 Swift 4.1 中解析任意 JSON
- html - input type="file" 导致 iphone 横屏溢出