向所有人致意。 我对数据表以及如何表示JSON还是很陌生,所以我会借助那些了解的人的经验。
我有一个服务器,该服务器以JSON返回数据,我想在具有以下列的表中显示它们:
<td>Time</td>
<td>hostname</td>
<td>cpu</td>
<td>mem</td>
<td>load</td>
<td>disk</td>
因此,我将其称为JSON响应:
$(document).ready(function() {
var table = $('#example').DataTable( {
"ajax": {
"url": "http://les000/query?db=tele&q=SELECT LAST(cpu_used) AS cpu, LAST(mem_used) AS mem, LAST(load) AS load, LAST(disk_await) AS disk_await FROM custom GROUP BY hostname ORDER BY time",
"dataType": "json",
"cache": false,
"contentType": "application/json; charset=utf-8"
deferRender: true,
columns: [
{data: 'time' },
{ data: 'hostname' },
{ data: 'cpu' },
{ data: 'mem' },
{ data: 'load' },
{ data: 'disk' }
],
rowId: 'extn',
select: true,
dom: 'Bfrtip',
buttons: [
{
text: 'Reload table',
action: function () {
table.ajax.reload();
}
}
]
} );
} );
我得到以下答案:
Métodode lapetición:GET 电子邮件:HTTP / 1.1 200 OK
这是我得到的JSON:
{
"results": [{
"statement_id": 0,
"series": [{
"name": "custom",
"tags": {
"hostname": "LINUX2345"
},
"columns": ["time", "cpu", "mem", "load", "disk_await"],
"values": [
["1970-01-01T00:00:00Z", 1, 78, 0, 0]
]
}, {
"name": "custom",
"tags": {
"hostname": "LINUX344334"
},
"columns": ["time", "cpu", "mem", "load", "disk_await"],
"values": [
["1970-01-01T00:00:00Z", 9, 49, 1, 0]
]
}]
}]
}
但是在桌子上我什么都没有。
有人可以引导我吗?谢谢。
答案 0 :(得分:0)
这是一个完整的工作示例: HTML
<div class="container">
<div class="panel">
<button id="loadData" class="btn btn-default">Load Data</button>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Occupation</th>
<th>Email Address</th>
</tr>
</thead>
</table>
</div>
</div>
JS:
$(function() {
$("#example").DataTable();
// Premade test data, you can also use your own
var testDataUrl = "https://raw.githubusercontent.com/chennighan/RapidlyPrototypeJavaScript/master/lesson4/data.json"
$("#loadData").click(function() {
loadData();
});
function loadData() {
$.ajax({
type: 'GET',
url: testDataUrl,
contentType: "text/plain",
dataType: 'json',
success: function (data) {
myJsonData = data;
populateDataTable(myJsonData);
},
error: function (e) {
console.log("There was an error with your request...");
console.log("error: " + JSON.stringify(e));
}
});
}
// populate the data table with JSON data
function populateDataTable(data) {
console.log("populating data table...");
// clear the table before populating it with more data
$("#example").DataTable().clear();
var length = Object.keys(data.customers).length;
for(var i = 1; i < length+1; i++) {
var customer = data.customers['customer'+i];
// You could also use an ajax property on the data table initialization
$('#example').dataTable().fnAddData( [
customer.first_name,
customer.last_name,
customer.occupation,
customer.email_address
]);
}
}
})();
**注意:您需要包含Jquery和数据表脚本(即CDN链接中的脚本)