javascript 带有 JSON 数据的数据表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51023879/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
DataTable with JSON data
提问by Onextrapixel
I am trying to create a table using DataTable but having a hard time getting DataTable to load with JSON object.
我正在尝试使用 DataTable 创建一个表,但是很难让 DataTable 加载 JSON 对象。
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();
}
Requesting the JSON file via a XMLHttpRequest() request.
通过 XMLHttpRequest() 请求请求 JSON 文件。
short sample of the JSON object:
JSON 对象的简短示例:
{
"meta": {
"version": 1,
"type": "test"
},
"reports": [
{
"report-metadata": {
"timestamp": 1528235303.721987,
"from-ip": "0.0.0.0"
},
//and so on...
Currently only trying to show the metapart in a DataTable table:
目前只尝试在 DataTable 表中显示元部分:
function createTable(jsonData){
$(document).ready(function(){
$('#table').dataTable({
data: jsonData,
columns: [
{ data: 'meta.type' },
{ data: 'meta.version' }
]
});
});
}
index.htmlpart:
index.html部分:
<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.
运行时只得到表中无可用数据,我显然遗漏了一些东西。
回答by Preston
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.
用于初始化数据表的“数据”属性需要一个列表(每个元素代表一行)。修改你的 ajax 响应,让每一行都是 jsonData 列表中的一个元素。我还在所有 JSON 选项周围添加了引号。
var jsonData = [
{ "meta": { "version": 1, "type": "test" } }
];
$('#table').DataTable({
"data": jsonData,
"columns": [
{ "data": "meta.type" },
{ "data": "meta.version" }
]
});
https://datatables.net/reference/option/data
https://datatables.net/reference/option/data
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
由于您想通过 ajax 加载数据,您应该查看内置在 DataTables API 中的 ajax 选项。https://datatables.net/manual/ajax

