扩展 Kamal Deep Singh 所说的内容:
您可以动态创建表,然后对其应用数据表以获取数据表的功能。
// up in the html
<table id="myDatatable" class="... whatever you need..."></table>
然后:
// in the javascript, where you would ordinarily initialize the datatable
var newTable = '<thead><tr>'; // start building a new table contents
// then call the data using .ajax()
$.ajax( {
url: "http://my.data.source.com",
data: {}, // data, if any, to send to server
success: function(data) {
// below use the first row to grab all the column names and set them in <th>s
$.each(data[0], function(key, value) {
newTable += "<th>" + key + "</th>";
});
newTable += "</tr></thead><tbody>";
// then load the data into the table
$.each(data, function(key, row) {
newTable += "<tr>";
$.each(row, function(key, fieldValue) {
newTable += "<td>" + fieldValue + "</td>";
});
newTable += "</tr>";
});
newTable += '<tbody>';
$('#myDatatable').html(newTable); // replace the guts of the datatable's table placeholder with the stuff we just created.
}
});
// Now that our table has been created, Datatables-ize it
$('#myDatatable').dataTable();
请注意,您可以像往常一样将设置放入该 .dataTable() 中,但是,不能将 'sAjaxSource' 或任何相关的数据获取函数 - 这是将数据表应用到已经存在的表中,这是我们动态创建的表.
好的,这是一种很老套的做法,但应该可以。
目前还没有内置的方法来动态处理数据表。见这里:https://github.com/DataTables/DataTables/issues/273