How to refresh DataTables

2020-05-21 05:44发布

I am using DataTables plugin to make my table interactive.

The table is echo'd by PHP on the page.

When I add a record to the DB I am loading the table using jQuery load() but this breaks DataTables.

How can I update the table while still keeping DataTables Intact?

Note: I am using DOM as the data source and not server side processing.

3条回答
爷的心禁止访问
2楼-- · 2020-05-21 06:10

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".

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();
}); 
查看更多
对你真心纯属浪费
3楼-- · 2020-05-21 06:13

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:

success: function(response){
    table.fnAddData([
        response.id,
        response.name,
        response.description,
    ]);
}

You can read more about the fnAddData method here.

查看更多
我命由我不由天
4楼-- · 2020-05-21 06:16

You should be able to use the ajax plugin. http://datatables.net/plug-ins/api

查看更多
登录 后发表回答