Reinitialize datatable using the new API

2019-08-15 02:15发布

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条回答
乱世女痞
2楼-- · 2019-08-15 03:02

Use the destroy option :

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

reinitialise with new data and removed search capabilities .

$("#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/

If you use an options literal you must reset it before reusing it :

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();
});

This is because the options object is enriched with different values such as aaData, aoColumns an so on, which will conflict if you specify new data and new columns.

查看更多
登录 后发表回答