如何重新初始化数据表

How do I reinitialise a Datatable?

本文关键字:数据表 初始化 何重新      更新时间:2023-09-26

我有一个页面,上面有通知,我想每10秒刷新一次,但我不想重新加载整个页面,只想重新加载包含通知的div。通知本身在一个数据表中,该数据表在加载页面时进行初始化,但我无法在重新加载div时让它重新初始化数据表。div很好地重新加载,但它只是一个普通的表。这是我的代码:

$(document).ready(function () {
    loadNotificationsTable();
});
setInterval(reloadNotificationsTable, 10000);
function reloadNotificationsTable() {
    $('#NotificationsTable').dataTable().fnDestroy();
    $("#notificationsPlaceholder").load(location.href + " #notificationsPlaceholder>*", "");
    $("#notificationsPlaceholder").ready(function () {
        loadNotificationsTable();
    });
};
function loadNotificationsTable() {
    $('#NotificationsTable').dataTable({
        ajax: "data.json",
        "bLengthChange": false,
        'iDisplayLength': 1000,
        "bSort": false,
        "bFilter": false,
        "sDom": 'ft<"bottom"ilp>',
        "bDestroy": false,
        "bPaginate": false,
        "bInfo":false
    });
};

有人能帮我看看我做错了什么吗?

在回调中load完成后,尝试重新初始化数据表:

$("#notificationsPlaceholder").load(location.href + " #notificationsPlaceholder>*",function(data){
    loadNotificationsTable();
});

还要将其添加到初始化代码中因为你想替换表

https://legacy.datatables.net/ref#bDestroy

"bDestroy": true,

如果需要定期刷新表,请使用以下方法:

$('#table_id').DataTable().ajax.reload();

将此代码与setTimeout()函数一起使用,可以定期刷新数据表。