我有一个数据表,响应来自API。现在我想在该数据表中显示该信息。 回复如下
[
{
"server_id": "123.123.12.12",
"domain": null,
"count_date": "2018-03-02",
"bounce_count": "281494",
"deliver_count": "558350"
},
{
"server_id": "123.123.12.12",
"domain": null,
"count_date": "2018-03-03",
"bounce_count": "1",
"deliver_count": "0"
},
{
"server_id": "123.123.12.12",
"domain": "test.com",
"count_date": "2018-03-05",
"bounce_count": "444",
"deliver_count": "194747"
},
]
我想在数据表中填充上述信息,以便该json的键是表头和下面行中的值
答案 0 :(得分:1)
您可以使用以下代码根据Ajax结果显示Jquery数据表。
假设你进行了一次Ajax调用,并且你的数据是结果变量(这里我把它作为常量给出)
$(document).ready(function() {
var result = [
{
"server_id": "123.123.12.12",
"domain": null,
"count_date": "2018-03-02",
"bounce_count": "281494",
"deliver_count": "558350"
},
{
"server_id": "123.123.12.12",
"domain": null,
"count_date": "2018-03-03",
"bounce_count": "1",
"deliver_count": "0"
},
{
"server_id": "123.123.12.12",
"domain": "test.com",
"count_date": "2018-03-05",
"bounce_count": "444",
"deliver_count": "194747"
},
]
LoadCurrentData(result)
} );
function LoadCurrentData(result) {
var example = $("#example")
// "server_id": "123.123.12.12",
// "domain": "test.com",
// "count_date": "2018-03-05",
// "bounce_count": "444",
// "deliver_count": "194747"
example.DataTable ({
"data" : result,
"columns" : [
{ "data" : "server_id"},
{ "data" : "domain" },
{ "data" : "count_date" },
{ "data" : "bounce_count" },
{ "data" : "deliver_count" }
]
});
}

<link href="https://cdn.datatables.net/1.10.9/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js"></script>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Server_id</th>
<th>domain</th>
<th>count_date</th>
<th>bounce_count</th>
<th>deliver_count</th>
</tr>
</thead>
</table>
&#13;
如果您正在寻找
,请告诉我答案 1 :(得分:0)
如果你不知道&#34;形状&#34;你的数据可以做这样的事情:
var data = [{
"server_id": "123.123.12.12",
"domain": null,
"count_date": "2018-03-02",
"bounce_count": "281494",
"deliver_count": "558350"
},
{
"server_id": "123.123.12.12",
"domain": null,
"count_date": "2018-03-03",
"bounce_count": "1",
"deliver_count": "0"
},
{
"server_id": "123.123.12.12",
"domain": "test.com",
"count_date": "2018-03-05",
"bounce_count": "444",
"deliver_count": "194747"
}
];
var example = null;
$.ajax({
type: 'POST',
dataType: 'json',
url: '/echo/json/',
data: {
json: JSON.stringify(data)
},
success: function(result) {
var arr = [],
cols = [];
result.reduce(function(pre, item) {
Object.keys(item).forEach(function(i) {
if (arr.indexOf(i) === -1) {
arr.push(i);
cols.push({
"data": i,
"title": i,
"default": ""
});
}
});
});
if ($.fn.DataTable.isDataTable("#example")) {
example.destroy();
$('#example').empty();
}
example = $("#example").DataTable({
"responsive": true,
"columns": cols,
"data": result,
"autoWidth": false
});
}
});
使用JSFiddle here。可能有更优雅的方法来生成列数组...
您的ajax
调用可能会有所不同,因为这是使用JSFiddle的模拟ajax
机制。