进行接听电话时更新DataTable

发布于 2025-02-02 00:55:06 字数 4840 浏览 3 评论 0原文

这是我要在:

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

在我的基本代码中 应用DataTable的表在表中显示它们。

 $('#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);

我遇到的问题是关于数据的。 当我第一次加载页面时,我在数据表中获取正确的数据: 1 但是,当我更改DEDATER时,数据确实会得到刷新,但是作为正常表,好像数据不存在(没有分页,所有元素都显示在HTML上,没有分页选项)。 有没有办法将其修复,以便每当我更改DataTable内部的数据更新日期?

This is the table i want to apply DataTable on :

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

In my basic code, i have a dateRangePicker that displays the calendar, and based on the interval of dates chosen, there will be a fetch method to my server to fetch data from the database and display them in the 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);

The problem that i have is regarding the datatable.
When i first load the page, i get the correct data in the DataTable :
1
But when i change the daterange, the data does get refreshed but as a normal table as if the DataTable doesn't exist(there is no pagination and all the elements are displayed on html with no pagination option).
Is there a way to fix it as to whenever i change the date the data updates INSIDE the datatable ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

晨曦慕雪 2025-02-09 00:55:06

基本上,您需要在将新行(动态)插入表之后重新定位数据。

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

这是基于您的代码的工作片段,单击“填充”按钮将触发该过程:

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>

You basically need to re-initialize DataTable after you insert new rows (dynamically) to your table.

To achieve this, DataTable lets you destroy() the original table you built, and then initialize it again.

Here is a working snippet based on your code, clicking the "populate" button will trigger the procedure:

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>

落花浅忆 2025-02-09 00:55:06

还有另一个答案是要添加:

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

There is also another answer to it which is to add :

$('#all_users').DataTable().clear().destroy();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文