我在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获取并将其作为一个很好的表显示给用户? 谢谢!
答案 0 :(得分:3)
$.parseJSON
(或 JSON.parse
)解析JSON字符串或设置 dataType : 'json'
< / LI>
$.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>