如何使用新的 JSON 数据手动更新数据表 [英] How to manually update datatables table with new JSON data
问题描述
我正在使用插件 jQuery 数据表 并加载我在页面底部的 DOM 中加载的数据并启动插件这样:
I am using plugin jQuery datatables and load my data which I have loaded in DOM at the bottom of page and initiates plugin in this way:
var myData = [
{
"id": 1,
"first_name": "John",
"last_name": "Doe"
}
];
$('#table').dataTable({
data: myData
columns: [
{ data: 'id' },
{ data: 'first_name' },
{ data: 'last_name' }
]
});
现在.执行某些操作后,我想使用 ajax 获取新数据(但不是数据表中的 ajax 选项构建 - 不要误会!)并使用这些数据更新表.我如何使用数据表 API 做到这一点?文档非常混乱,我找不到解决方案.任何帮助将不胜感激.谢谢.
Now. after performing some action I want to get new data using ajax (but not ajax option build in datatables - don't get me wrong!) and update the table with these data. How can i do that using datatables API? The documentation is very confusing and I can not find a solution. Any help will be very much appreciated. Thanks.
推荐答案
解决方案:(注意:此解决方案适用于数据表版本 1.10.4(目前)而不是旧版本).
SOLUTION: (Notice: this solution is for datatables version 1.10.4 (at the moment) not legacy version).
澄清根据 API 文档 (1.10.15),API可以通过三种方式访问:
CLARIFICATION Per the API documentation (1.10.15), the API can be accessed three ways:
DataTables 的现代定义(驼峰大写):
The modern definition of DataTables (upper camel case):
var datatable = $( selector ).DataTable();
DataTables 的旧定义(驼峰式小写):
The legacy definition of DataTables (lower camel case):
var datatable = $( selector ).dataTable().api();
使用 new
语法.
var datatable = new $.fn.dataTable.Api( selector );
然后像这样加载数据:
$.get('myUrl', function(newDataArray) {
datatable.clear();
datatable.rows.add(newDataArray);
datatable.draw();
});
使用draw(false)
在数据更新后保持在同一页面.
Use draw(false)
to stay on the same page after the data update.
API 参考:
https://datatables.net/reference/api/clear()
https://datatables.net/reference/api/rows.add()
https://datatables.net/reference/api/draw()
这篇关于如何使用新的 JSON 数据手动更新数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!