javascript 如何将动态 json 加载到 jquery 数据表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31249641/
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
how to load dynamic json to jquery datatable
提问by Allen4Tech
I want to load dynamic data into my jquery datatable. That means, before I get the json data from server, I don't know what fields it contains, but I'm sure the json is valid. It will looks like below,
我想将动态数据加载到我的 jquery 数据表中。这意味着,在我从服务器获取 json 数据之前,我不知道它包含哪些字段,但我确定 json 是有效的。它看起来像下面,
"data": [
{
"first_name": "Airi",
"last_name": "Satou",
"position": "Accountant",
"office": "Tokyo",
"start_date": "28th Nov 08",
"salary": "2,700"
},
{
"first_name": "Angelica",
"last_name": "Ramos",
"position": "Chief Executive Officer (CEO)",
"office": "London",
"start_date": "9th Oct 09",
"salary": ",200,000"
}
]
]
sometimes, it may only contains 'first_name' and 'last_name'.
有时,它可能只包含“first_name”和“last_name”。
I've searched a long time, all of the samples specify 'aoColumnsDef' or 'aoColumns'. But I don't know the exact fileds. Is there a way to fill jquery datatable using the field name in json as the header of the table and the field value as the body of the table? For example, the json data only contains two fields, 'first_name' and 'last_name', the table should contains two columns 'first_name' and 'last_name'. If the json contains 3 fields, the table should display the 3 columns. I'm sure all of the items in "data" have the same fields.
我已经搜索了很长时间,所有样本都指定了“aoColumnsDef”或“aoColumns”。但我不知道确切的文件。有没有办法使用json中的字段名作为表头,字段值作为表体来填充jquery数据表?例如json数据只包含'first_name'和'last_name'两个字段,表中应该包含'first_name'和'last_name'两列。如果 json 包含 3 个字段,则该表应显示 3 列。我确定“数据”中的所有项目都具有相同的字段。
Thanks in advance!
提前致谢!
采纳答案by BLSully
Using your example data, loop over the first record as your 'example' data, then create the column definitions on the fly like so:
使用您的示例数据,循环第一条记录作为您的“示例”数据,然后像这样动态创建列定义:
EDIT: example of original code with an xhr call to retrieve data
编辑:使用 xhr 调用检索数据的原始代码示例
$(document).ready(function() {
//callback function that configures and initializes DataTables
function renderTable(xhrdata) {
var cols = [];
var exampleRecord = xhrdata[0];
var keys = Object.keys(exampleRecord);
keys.forEach(function(k) {
cols.push({
title: k,
data: k
//optionally do some type detection here for render function
});
});
var table = $('#example').DataTable({
columns: cols
});
table.rows.add(xhrdata).draw();
}
//xhr call to retrieve data
var xhrcall = $.ajax('/path/to/data');
//promise syntax to render after xhr completes
xhrcall.done(renderTable);
});
var data = [{
"first_name": "Airi",
"last_name": "Satou",
"position": "Accountant",
"office": "Tokyo",
"start_date": "28th Nov 08",
"salary": "2,700"
},
{
"first_name": "Angelica",
"last_name": "Ramos",
"position": "Chief Executive Officer (CEO)",
"office": "London",
"start_date": "9th Oct 09",
"salary": ",200,000"
}];
$(document).ready( function () {
var cols = [];
var exampleRecord = data[0];
//get keys in object. This will only work if your statement remains true that all objects have identical keys
var keys = Object.keys(exampleRecord);
//for each key, add a column definition
keys.forEach(function(k) {
cols.push({
title: k,
data: k
//optionally do some type detection here for render function
});
});
//initialize DataTables
var table = $('#example').DataTable({
columns: cols
});
//add data and draw
table.rows.add(data).draw();
});
body {
font: 90%/1.45em "Helvetica Neue", HelveticaNeue, Verdana, Arial, Helvetica, sans-serif;
margin: 0;
padding: 0;
color: #333;
background-color: #fff;
}
div.container {
min-width: 980px;
margin: 0 auto;
}
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<link href="//datatables.net/download/build/nightly/jquery.dataTables.css" rel="stylesheet" type="text/css" />
<script src="//datatables.net/download/build/nightly/jquery.dataTables.js"></script>
<meta charset=utf-8 />
<title>DataTables - JS Bin</title>
</head>
<body>
<div class="container">
<table id="example" class="display" width="100%">
</table>
</div>
</body>
</html>
回答by Sargon
How about build a simple html table from received JSON first and only after this build DataTable using created table.
如何首先从接收到的 JSON 构建一个简单的 html 表,并且只有在使用创建的表构建 DataTable 之后。
var table = $("#tableId");
table.append('<thead>....</thead>');
table.append('<tbody>....</tbody>');
table.DataTable();