首页 > 解决方案 > 使用 AJAX 和数据表刷新数据表

问题描述

我是 Web 开发的新手,实际上我正在使用 Codeigniter 和 Bootstrap 开发一些仪表板。我有一个问题,我需要输出一个包含大量数据的数据表,所以我想使用 Datatables。问题是,第一次加载页面时,一切正常,但在 AJAX 刷新后,我失去了数据表中的分页和 JavaScript。

现在我正在使用此代码来创建表:

function refreshTabellaApple() {
    $('#tabellaApple').empty();
    $.ajax({
        method: "POST",
        url: base_url + 'dashboard/ajax_tabella_apple',
        success: function(data) {

            var tbody = $("<tbody />"),
                thead = $("<thead><tr><th class='m-0 font-weight-bold text-primary h5'>Data Recensione</th><th class='m-0 font-weight-bold text-primary h5 text-center'>Utente</th><th class='m-0 font-weight-bold text-primary h5 text-center'>Titolo</th><th class='m-0 font-weight-bold text-primary h5 text-center'>Recensione</th><th class='m-0 font-weight-bold text-primary h5 text-center'>Risposta</th></tr></thead>"),
                tr;
            $.each(JSON.parse(data), function(_, obj) {
                tr = $("<tr />");

                tr
                    .append("<td class='m-0'>" + obj.dt_datarecensione + "</td>")
                    .append("<td class='m-0'>" + obj.utente + "</td>")
                    .append("<td class='m-0'>" + obj.titolo + "</td>")
                    .append("<td class='m-0'>" + obj.recensione + "</td>")
                    .append("<td class='m-0'>" + obj.risposta + "</td>")

                tr.appendTo(tbody);
            });
            $('#tabellaApple').append(thead);
            $('#tabellaApple').append(tbody);
            setTimeout(function() {
                refreshTabellaApple(); //this will send request again and again;
            }, 30000);
        }

    });

};
refreshTabellaApple();

如您所见,我正在 JavaScript 中构建表格主体,然后每 30 秒刷新一次。在另一个 js 文件中,我将该表称为 Datatable

<script type="text/javascript">
    $(document).ready(function() {
        $('#tabellaApple').DataTable();
    });
</script>

如何使用 Datatables 重建函数 refreshTabellaApple?

标签: javascriptjquerydatatables

解决方案


推荐阅读