我在 jQuery 中有以下代码:
$.ajax({
url: './getJson.php',
type: "POST",
data: {
email: email
},
dataType:'text',
success: function(response)
{
alert(response)
}
});
在我的网页上运行它后,我会看到一个包含 json 数据的弹出窗口,其结构如下:
[{"number":"1","id":"2","price":"100.70","date":"2015-10-18 03:00:00"},
{"number":"2","id":"2","price":"88.20","date":"2015-10-18 04:00:00"}]
当用户进入我的页面时就会发生这种情况。相反,我想用该数据填充 html 表,并且布局已经准备好(到目前为止填充了虚拟数据):
<div class="panel-body">
<div class="dataTable_wrapper">
<table class="table table-striped table-bordered table-hover" id="dataTables-example">
<thead>
<tr>
<th>number</th>
<th>id</th>
<th>price</th>
<th>date</th>
</tr>
</thead>
<tbody>
<tr class="odd gradeX">
<td>Trident</td>
<td>Internet Explorer 4.0</td>
<td>Win 95+</td>
<td class="center">4</td>
</tr>
<tr class="even gradeC">
<td>Trident</td>
<td>Internet Explorer 5.0</td>
<td>Win 95+</td>
<td class="center">5</td>
</tr>
<tr class="odd gradeA">
<td>Trident</td>
<td>Internet Explorer 5.5</td>
<td>Win 95+</td>
<td class="center">5.5</td>
</tr>
现在我的问题是 - 如何用我自己的从 json 获取的虚拟数据替换虚拟数据,并将其始终作为一个漂亮的表格显示给用户? 谢谢!
最佳答案
- 使用
$.parseJSON
解析 JSON 字符串 (或JSON.parse
)或设置dataType : 'json'
- 使用
$.each()
迭代解析的对象 - 生成
tr
包含内容并使用appendTo()
将其附加到表格中 或append()
。
var data = '[{"number":"1","id":"2","price":"100.70","date":"2015-10-18 03:00:00"},{"number":"2","id":"2","price":"88.20","date":"2015-10-18 04:00:00"}]';
json = JSON.parse(data);
$.each(json, function(i, v) {
$('<tr/>', {
html: [$('<td/>', {
text: v.number
}), $('<td/>', {
text: v.id
}), $('<td/>', {
text: v.price
}), $('<td/>', {
text: v.date
})]
}).appendTo('#dataTables-example tbody')
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="panel-body">
<div class="dataTable_wrapper">
<table class="table table-striped table-bordered table-hover" id="dataTables-example">
<thead>
<tr>
<th>number</th>
<th>id</th>
<th>price</th>
<th>date</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
关于javascript - 如何在 jquery 中将 json 数据转换为 html 表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33201001/