带有JSON数据的DataTable [英] DataTable with JSON data
问题描述
我正在尝试使用DataTable创建一个表,但很难让DataTable加载JSON对象。
I am trying to create a table using DataTable but having a hard time getting DataTable to load with JSON object.
function getData() {
var request = new XMLHttpRequest();
var json = "link-to-my-json-object";
// Get JSON file
request.onload = function() {
if ( request.readyState === 4 && request.status === 200 ) {
var JSONObject = JSON.parse(request.responseText);
createTable(JSONObject);
} else if(request.status == 400) { console.log("Error", request.status);}
};
request.open("GET", json, true);
request.send();
}
通过XMLHttpRequest()请求请求JSON文件。
Requesting the JSON file via a XMLHttpRequest() request.
JSON对象的简短示例:
short sample of the JSON object:
{
"meta": {
"version": 1,
"type": "test"
},
"reports": [
{
"report-metadata": {
"timestamp": 1528235303.721987,
"from-ip": "0.0.0.0"
},
//and so on...
目前只尝试在DataTable表中显示 meta 部分:
Currently only trying to show the meta part in a DataTable table:
function createTable(jsonData){
$(document).ready(function(){
$('#table').dataTable({
data: jsonData,
columns: [
{ data: 'meta.type' },
{ data: 'meta.version' }
]
});
});
}
index.html part:
<table id="table" class="display" style="width:100%"></table>
运行时只有表中没有数据可用,我显然遗漏了一些东西。
Only getting a No data available in table when running, and I am obviously missing something.
推荐答案
初始化数据表的data属性需要一个列表(每个元素代表一行)。修改您的ajax响应,因此每一行都是jsonData列表中的一个元素。我还在所有JSON选项周围添加了引号。
The "data" attribute for initializing your Data Table is expecting a list (Each element representing a row). Modify your ajax response, so each row is an element in the jsonData list. I also added quotes around all the JSON options.
var jsonData = [
{ "meta": { "version": 1, "type": "test" } }
];
$('#table').DataTable({
"data": jsonData,
"columns": [
{ "data": "meta.type" },
{ "data": "meta.version" }
]
});
https://datatables.net/reference/option/data
由于你想通过ajax加载你的数据,你应该看看在DataTables API内置的ajax选项中。 https://datatables.net/manual/ajax
Since you want to load your data via ajax, you should look at the ajax options built in to the DataTables API. https://datatables.net/manual/ajax
这篇关于带有JSON数据的DataTable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!