为什么我的HTML表在用Ajax刷新时会丢失引导数据表属性?

时间:2019-08-13 23:45:14

标签: javascript jquery html ajax datatables

我有一个HTML表存储在 table.html:

<table id="example" class="table table-striped table-bordered" style="width:100%">
        <thead>
            <tr>
                <th>Name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Age</th>
                <th>Start date</th>
                <th>Salary</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>Tiger Nixon</td>
                <td>System Architect</td>
                <td>Edinburgh</td>
                <td>61</td>
                <td>2011/04/25</td>
                <td>$320,800</td>
            </tr>
</table>

以及另一个包含名为“ newtable”的div的页面,使用ajax脚本获取table.html的内容,将其插入名为“ newtable”的div中,并每5秒钟刷新一次。 该表使用引导程序数据表,这为我的表添加了搜索框和分页功能:

<body>
<div class="content table-responsive table-full-width newtable">

</div>
</body>

    <script>
        function table() {
            $.ajax({
                url: 'table.html',
                type: 'get',
                success: function(response){
                    $('.newtable').html(response);
                }
            });
        }

                table();
        setInterval(table, 5000);

$(document).ready(function() {
    $('#example').DataTable();
} );


    </script>
</html>

当页面加载时,我的表工作正常,但是在ajax刷新表内容之后,该表更新,但是bootstrap datatables函数(搜索栏和分页)消失了,除非我自己刷新页面,否则不会重新出现

如何解决此问题?

1 个答案:

答案 0 :(得分:2)

调用$('.newtable').html(response)时,它将修改表的内容以添加所有功能。但是,由于您的ajax调用正在更改表的内部HTML(DataTable()),因此所有内容都会丢失。加载新数据后,您可以再次调用success: function(response){ $('.newtable').html(response); $('.newtable').DataTable(); }

else