jQuery 使用ajax刷新表格内容后重绘数据表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7819036/
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
Redraw datatables after using ajax to refresh the table content?
提问by Anagio
I am using Datatablesand have a button on the page that refreshes the table using AJAX. To be clear the table isn't using an ajax source of data, we are just using ajax to refresh it only when needed. Ajax is refreshing the div which the table is wrapped in. I know i'm losing my pagination buttons and filtering capability because the table needs to be redrawn but i'm not sure how to add this into the table initialization code.
我正在使用数据表并在页面上有一个按钮,可以使用 AJAX 刷新表。要明确表没有使用 ajax 数据源,我们只是在需要时才使用 ajax 刷新它。Ajax 正在刷新表格所在的 div。我知道我正在失去分页按钮和过滤功能,因为表格需要重新绘制,但我不确定如何将其添加到表格初始化代码中。
Datatables code
数据表代码
var oTable6;
$(document).ready(function() {
oTable6 = $('#rankings').dataTable( {
"sDom":'t<"bottom"filp><"clear">',
"bAutoWidth": false,
"sPaginationType": "full_numbers",
"aoColumns": [
{ "bSortable": false, "sWidth": "10px" },
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null
]
});
});
The ajax code is this
ajax代码是这样的
$("#ajaxchange").click(function(){
var campaign_id = $("#campaigns_id").val();
var fromDate = $("#from").val();
var toDate = $("#to").val();
var url = 'http://domain.com/account/campaign/ajaxrefreshgrid?format=html';
$.post(url, { campaignId: campaign_id, fromdate: fromDate, todate: toDate},
function( data ) {
$("#ajaxresponse").html(data);
});
});
I tried this but it didn't work
我试过这个,但没有用
"fnDrawCallback": function() {
function( data ) {
$("#ajaxresponse").html(data);
};
},
回答by swatkins
It looks as if you could use the API functions to
看起来好像您可以使用 API 函数来
- clear the table ( fnClearTable )
- add new data to the table ( fnAddData)
- redraw the table ( fnDraw )
- 清除表格( fnClearTable )
- 向表中添加新数据 (fnAddData)
- 重绘表格 ( fnDraw )
UPDATE
更新
I guess you're using the DOM Data Source(for server-side processing) to generate your table. I didn't really get that at first, so my previous answer won't work for that.
我猜您正在使用DOM 数据源(用于服务器端处理)来生成您的表。一开始我并没有真正明白这一点,所以我之前的答案对此不起作用。
To get it to work without rewriting your server side code:
要在不重写服务器端代码的情况下使其工作:
What you'll need to do is totally remove the old table (in the dom) and replace it with the ajax result content, then reinitialize the datatable:
您需要做的是完全删除旧表(在 dom 中)并将其替换为 ajax 结果内容,然后重新初始化数据表:
// in your $.post callback:
function (data) {
// remove the old table
$("#ajaxresponse").children().remove();
// replace with the new table
$("#ajaxresponse").html(data);
// reinitialize the datatable
$('#rankings').dataTable( {
"sDom":'t<"bottom"filp><"clear">',
"bAutoWidth": false,
"sPaginationType": "full_numbers",
"aoColumns": [
{ "bSortable": false, "sWidth": "10px" },
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null
]
}
);
}
回答by Keith.Abramo
Try destroying the datatable with bDestroy:true like this:
尝试使用 bDestroy:true 销毁数据表,如下所示:
$("#ajaxchange").click(function(){
var campaign_id = $("#campaigns_id").val();
var fromDate = $("#from").val();
var toDate = $("#to").val();
var url = 'http://domain.com/account/campaign/ajaxrefreshgrid?format=html';
$.post(url, { campaignId: campaign_id, fromdate: fromDate, todate: toDate},
function( data ) {
$("#ajaxresponse").html(data);
oTable6 = $('#rankings').dataTable( {"bDestroy":true,
"sDom":'t<"bottom"filp><"clear">',
"bAutoWidth": false,
"sPaginationType": "full_numbers",
"aoColumns": [
{ "bSortable": false, "sWidth": "10px" },
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null
]
}
);
});
});
bDestroy: true will first destroy and datatable instance associated with that selector before reinitializing a new one.
bDestroy: true 将首先销毁与该选择器关联的数据表实例,然后再重新初始化一个新实例。
回答by jairobg
I'm not sure why. But
我不知道为什么。但
oTable6.fnDraw();
Works for me. I put it in the next line.
为我工作。我把它放在下一行。
回答by Avram Cosmin
Use this:
用这个:
var table = $(selector).dataTables();
table.api().draw(false);
or
或者
var table = $(selector).DataTables();
table.draw(false);
回答by Anne Gunn
For users of modern DataTables (1.10 and above), all the answers and examples on this page are for the old api, not the new. I had a very hard time finding a newer example but finally did find this DT forum post(TL;DR for most folks) which led me to this concise example.
对于现代 DataTables(1.10 及更高版本)的用户,此页面上的所有答案和示例均针对旧 API,而非新 API。我很难找到一个更新的例子,但最终找到了这个 DT 论坛帖子(TL;大多数人的 DR),这让我找到了这个简洁的例子。
The example code worked for me after I finally noticed the $() selector syntax immediately surrounding the html string. You have to add a node not a string.
在我终于注意到 html 字符串周围的 $() 选择器语法后,示例代码对我有用。您必须添加节点而不是字符串。
That example really is worth looking at but, in the spirit of SO, if you just want to see a snippet of code that works:
该示例确实值得一看,但是,本着 SO 的精神,如果您只想查看一段有效的代码:
var table = $('#example').DataTable();
table.rows.add( $(
'<tr>'+
' <td>Tiger Nixon</td>'+
' <td>System Architect</td>'+
' <td>Edinburgh</td>'+
' <td>61</td>'+
' <td>2011/04/25</td>'+
' <td>,120</td>'+
'</tr>'
) ).draw();
The careful reader might note that, since we are adding only one row of data, that table.row.add(...) should work as well and did for me.
细心的读者可能会注意到,由于我们只添加了一行数据,因此 table.row.add(...) 应该也能正常工作并且对我有用。
回答by Imran Rashid
This works for me
这对我有用
var dataTable = $('#HelpdeskOverview').dataTable();
var oSettings = dataTable.fnSettings();
dataTable.fnClearTable(this);
for (var i=0; i<json.aaData.length; i++)
{
dataTable.oApi._fnAddData(oSettings, json.aaData[i]);
}
oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
dataTable.fnDraw();
回答by laromicas
In the initialization use:
在初始化中使用:
"fnServerData": function ( sSource, aoData, fnCallback ) {
//* Add some extra data to the sender *
newData = aoData;
newData.push({ "name": "key", "value": $('#value').val() });
$.getJSON( sSource, newData, function (json) {
//* Do whatever additional processing you want on the callback, then tell DataTables *
fnCallback(json);
} );
},
And then just use:
然后只需使用:
$("#table_id").dataTable().fnDraw();
The important thing in the fnServerData is:
fnServerData 中重要的是:
newData = aoData;
newData.push({ "name": "key", "value": $('#value').val() });
if you push directly to aoData, the change is permanent the first time you draw the table and fnDraw don't work the way you want.
如果您直接推送到 aoData,则在您第一次绘制表格时更改是永久性的,而 fnDraw 不会按您想要的方式工作。
回答by Igor L.
This is how I feed my table with data retrieved by ajax (not sure if this is the best practice tough, but it feels intuitive and works well):
这就是我用 ajax 检索到的数据为我的表提供数据的方式(不确定这是否是最佳实践,但感觉很直观并且效果很好):
/* initialise table */
oTable1 = $( '.tables table' ).dataTable
( {
'sPaginationType': 'full_numbers',
'bLengthChange': false,
'aaData': [],
'aoColumns': [{"sTitle": "Tables"}],
'bAutoWidth': true
} );
/*retrieve data*/
function getArr( conf_csv_path )
{
$.ajax
({
url : 'my_url'
success : function( obj )
{
update_table( obj );
}
});
}
/* build table data */
function update_table( arr )
{
oTable1.fnClearTable();
for ( input in arr )
{
oTable1.fnAddData( [ arr[input] );
}
}