Reinitialize datatable using the new API

时间:2015-06-15 14:26:25

标签: javascript jquery datatables

I've found some SO threads about reinitializing a datatable using the old API, but I think they're deprecated now.

I have an existing rendered datatable. I would like to refresh it with new settings. Using the new API, how would I do the following:

var dataTable = $('table.dataTable').DataTable();

var newDataTableSettings = {
    data: { /* some data */ },
    columns: { /* some columns*/ },
    bFilter: false,
    // etc...
};

// something like dataTable.clear().data(newDataTableSettings).draw()

My closest attempt:

dataTable.clear().draw() 
dataTable.rows.add({ /* some data */ }).draw();

1 个答案:

答案 0 :(得分:4)

使用destroy选项:

$('#example').DataTable({
    data:  [{ test : 'test' }, { test : 'qwerty'}],    
    columns : [ { data : 'test', title: 'test' } ]    
});

重新初始化新数据并删除搜索功能。

$("#reinit").on('click', function() {
    $('#example').DataTable({
        destroy: true, //<--- here
        data: [{ newCol : '100010'}, { newCol : '234234'}],
        columns: [ { data : 'newCol', title: 'header' } ],
        searching: false
    })
});

http://jsfiddle.net/3sonfsfm/

如果您使用选项文字,则必须重置它才能重新使用它:

var options = {
    data:  [{ test : 'test' }, { test : 'qwerty'}],    
    columns : [ { data : 'test', title: 'test' } ]    
}

$("#reinit").on('click', function() {
    options = {}; //<--- RESET
    options.destroy = true;
    options.data = [{ newCol : '100010'}, { newCol : '234234'}];
    options.columns = [ { data : 'newCol', title: 'header' } ];
    options.searching = false;
    $('#example').DataTable(options).draw();
});

这是因为options对象增加了不同的值,例如aaDataaoColumns等等,如果您指定新的data和新{{} { {1}}。