jQuery 如何刷新数据表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9674560/
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 refresh DataTables
提问by Billy Martin
I am using DataTables plugin to make my table interactive.
我正在使用 DataTables 插件使我的表格具有交互性。
The table is echo'd by PHP on the page.
该表在页面上由 PHP 回显。
When I add a record to the DB I am loading the table using jQuery load() but this breaks DataTables.
当我向数据库添加记录时,我正在使用 jQuery load() 加载表,但这会破坏 DataTables。
How can I update the table while still keeping DataTables Intact?
如何在保持 DataTables 完整的同时更新表?
Note: I am using DOM as the data source and not server side processing.
注意:我使用 DOM 作为数据源而不是服务器端处理。
回答by charlietfl
If doing a complete reload of the whole table, wrap your initial datatables initialization code in a function. Call that function on page load. When replacing the table completely with ajax you likely should remove the table parent div that is created by plugin as a wrapper for all the non table DOm elements it creates. If table ID="example" , wrapper id="example_wrapper".
如果对整个表进行完整的重新加载,请将初始数据表初始化代码包装在一个函数中。在页面加载时调用该函数。当用 ajax 完全替换表时,您可能应该删除由插件创建的表父 div 作为它创建的所有非表 DOM 元素的包装器。如果表 ID="example" ,包装器 id="example_wrapper"。
Here's enough code will likely get you well on your way. There are easy ways to only update rows but since request is for a complete table reload I've followed that
这里有足够的代码可能会让你顺利。有一些简单的方法可以只更新行,但由于请求是重新加载完整的表,所以我遵循了这一点
function initDataTables(){
$('#myTable').datatables({/* put all current options here*/})
}
/* within ready event of pageload */
$(function(){
initDataTables();
/* all other page load code*/
});
/* use $.get to reload table */
$.get( tableUpdateUrl, data, function( returnData){
$('#myTable').parent().replaceWith(returnData);
/* re-initalize plugin*/
initDataTables();
});
回答by Mike Trpcic
When you create your data table, assign the resulting value into a variable:
创建数据表时,将结果值分配给变量:
var table = $(".something").dataTable();
When you create your new item, presumably via AJAX, make sure to return the properties that your table needs to display. Then, in your success
function, you can make use of the fnAddData
method to add a new row to your table. This method takes in an array of values, the first one goes in the first column, second in second, and so on:
当您创建新项目时,大概是通过 AJAX,确保返回您的表需要显示的属性。然后,在您的success
函数中,您可以使用该fnAddData
方法向表中添加新行。此方法接受一组值,第一个在第一列中,第二个在第二列中,依此类推:
success: function(response){
table.fnAddData([
response.id,
response.name,
response.description,
]);
}
You can read more about the fnAddData
method here.
您可以在此处阅读有关该fnAddData
方法的更多信息。
回答by JohnColvin
You should be able to use the ajax plugin. http://datatables.net/plug-ins/api
您应该能够使用 ajax 插件。http://datatables.net/plug-ins/api