执行提取调用时更新 DataTable

Update DataTable when doing fetch call

这是 table 我想在 :

上应用 DataTable
<div id="reportrange" style="background: #fff; cursor: pointer; padding: 5px 10px; border: 1px solid #ccc;">
<span></span>
</div>
<table id="all_users">
                        <thead>
                            <tr>
                                <th>User</th>
                                <th>Email</th>
                                <th>Country</th>
                                <th>City</th>
                                <th>Engaged sessions</th>
                                <th>Avg Session Duration</th>

                            </tr>
                        </thead>
                        <tbody id="table_body">
                        </tbody>
                    </table>

在我的基本代码中,我有一个显示日历的 dateRangePicker,根据所选日期的间隔,我的服务器将有一个获取方法从数据库中获取数据并将它们显示在 table.

 $('#reportrange').daterangepicker();
        $(function() {

            var start = moment().subtract(10, 'days');
            var end = moment();

            function cb(start, end) {
                $('#reportrange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
                let data = {
                    start_time: start.format('YYYY-MM-DD'),
                    end_time: end.format('YYYY-MM-DD')
                }
                let data_json = JSON.stringify(data)
                fetch("../backend/peopleExplorer1.php", {
                    method: 'POST',
                    headers: {
                        "Content-Type": "application/json",
                    },
                    body: data_json
                }).then(r => r.json()).then(r => {
                    let numbers_of_users_chart = r['numbers_of_users_chart'];
                    let avg_time_chart = r['avg_time_chart'];
                    let add_date = r['add_date'];

                    //fill the table
                    let name_users = r['name_current_user'];
                    let number_sessions = r['number_of_sessions'];
                    let avgtime = r['avg_time'];
                    let email = r['email'];
                    let country = r['country'];
                    let city = r['city'];
                    let users = [];
                    for (let i = 0; i < name_users.length; i++) {
                        users.push({
                            name: name_users[i],
                            email: email[i],
                            country: country[i],
                            city: city[i],
                            visit: number_sessions[i],
                            temps_moyenne: avgtime[i]
                        });
                    }
                    let tableData = "";

                    users.map((values) => {
                        tableData += ` <tr><td>${values.name}</td>
                                   <td>${values.email}</td>
                                   <td>${values.country}</td>
                                   <td>${values.city}</td>
                                   <td>${values.visit}</td>
                                   <td>${values.temps_moyenne} s</td>
                                </tr>`
                    })
                    $(document).ready(function() {
                        $('#all_users').dataTable({
                            "paging": true,
                        });
                        $('.dataTables_length').addClass('bs-select');

                    });
                    document.getElementById("table_body").innerHTML = tableData;
                })

            }

            $('#reportrange').daterangepicker({
                startDate: start,
                endDate: end,
                ranges: {
                    'Today': [moment(), moment()],
                    'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                    'Last 7 Days': [moment().subtract(6, 'days'), moment()],
                    'Last 30 Days': [moment().subtract(29, 'days'), moment()],
                    'This Month': [moment().startOf('month'), moment().endOf('month')],
                    'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
                }
            }, cb);

            cb(start, end);

我遇到的问题是关于数据的table。 当我第一次加载页面时,我在 DataTable 中得到了正确的数据: 1 但是当我更改日期范围时,数据确实会刷新,但作为正常 table 就好像 DataTable 不存在一样(没有分页,所有元素都显示在 html 上,没有分页选项). 有没有办法解决这个问题,无论何时我更改数据更新的日期 table?

在向 table 插入新行(动态)后,您基本上需要 re-initialize DataTable。

为此,DataTable 让您 destroy() 您构建的原始 table,然后再次初始化它。

这是一个基于您的代码的工作片段,点击“填充”按钮将触发程序:

const theTableBody = document.getElementById("table_body")

function populate() {
  let tableData = ''
  for (let i = 0; i < 20; i++) {
    tableData += `
      <tr>
      <td>${i}</td>
      <td>${i}</td>
      <td>${i}</td>
      <td>${i}</td>
      <td>${i}</td>
      <td>${i} s</td>
      </tr>`
  }
  theTableBody.innerHTML = tableData
}


var dataTableHandler = $('#all_users').DataTable({
  "paging": true,
})


$('#populateBtn').on('click', function(e) {
  // FIRST, WE DESTROY THE TABLE
  dataTableHandler.destroy()
  
  // SECOND, WE POPULATE THE TABLE WITH NEW ROWS
  populate()
  
  // THIRD, WE RE-INITIALIZE THE TABLE
  dataTableHandler = $('#all_users').DataTable({
    "paging": true,
  })
})
<link href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/js/jquery.dataTables.min.js"></script>



<button id="populateBtn">Dynamically populate the table</button>

<table id="all_users" border="1">
  <thead>
    <tr>
      <th>User</th>
      <th>Email</th>
      <th>Country</th>
      <th>City</th>
      <th>Engaged sessions</th>
      <th>Avg Session Duration</th>
    </tr>
  </thead>
  <tbody id="table_body">
  </tbody>
</table>

还有另一个答案是添加:

$('#all_users').DataTable().clear().destroy();