我正在尝试将一些简单的JSON数据加载到jQuery.DataTables(datatables.net)中,网格正在按HTML中的定义显示,但不会根据新数据而更改。
我想念什么?有什么建议吗?
HTML:
<table id="example" class="display" style="width:100%;">
<thead>
<tr>
<th>Id</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
</tr>
</tbody>
JavaScript :(已加载jQuery和jQuery.DataTables)
$(document).ready(function () {
$("#example").DataTable({
data: [{ Id: "1" }, { Id: "2" }],
columns: { data: "Id", title: "ID" }
});
});
答案 0 :(得分:0)
您的列数据应设置为Array。像这样
$(document).ready(function () {
$("#example").DataTable({
data: [{ Id: "1" }, { Id: "2" }],
columns: [{ data: "Id", title: "ID" }]
});
});
对于使用ajax的动态数据
$(document).ready(function() {
$('#example').DataTable( {
"ajax": "data/objects.txt",
"columns": [
{ "data": "name" },
{ "data": "position" },
{ "data": "office" },
{ "data": "extn" },
{ "data": "start_date" },
{ "data": "salary" }
]
} );
} );
JSON txt文件
{
"data": [
{
"id": "1",
"name": "Tiger Nixon",
"position": "System Architect",
"salary": "$320,800",
"start_date": "2011/04/25",
"office": "Edinburgh",
"extn": "5421"
},
{
"id": "2",
"name": "Garrett Winters",
"position": "Accountant",
"salary": "$170,750",
"start_date": "2011/07/25",
"office": "Tokyo",
"extn": "8422"
}
]
}
更多详细信息Here
答案 1 :(得分:0)
尝试一下
var options = {
data: [{ Id: "1" }, { Id: "2" }],
columns: { data: "Id", title: "ID" }
}
var dataTable = $("#example").DataTable(options );
// Reload and refresh
dataTable.draw();
答案 2 :(得分:0)
所以,我的用于注入JSON数据(或作为变量)的代码很好,问题是在网格初始化之前我忘记添加的另一个网格单击事件(不好的我)
$("#example " + "tbody").on("click", "tr", function () {
var data = table.row(this).data();
isDebug && console.log('You clicked on ' + data[0] + '\'s row');
isDebug && console.log(data);
});