datatable refreshes the data, js does not refresh the page as a whole, and uses the DataTables table plug-in to regularly update the background data changes


foreword

I recently encountered a need to refresh the real-time data display on a page. Of course, the easiest way is to add the http-equiv attribute of meta to the page header. This is the easiest way, but in this case, it will flash every time the page is refreshed. For a moment, the experience is not very good. Now I just want to update the data in a table instead of refreshing the entire page.


1. The http-equiv attribute of meta

If it is to refresh the entire page, using the following method is the simplest line to get it done.
<meta http-equiv="Refresh" content="10">
or:
<meta http-equiv="Refresh" content="10; URL=http://www.baidu.com/">
where 10 means After staying for 10 seconds, it will automatically refresh, if there is a URL, it will automatically refresh to this address.

Two, use the DataTables table plug-in

2.1. Overall idea

I found some ways to refresh the table. This is not like refreshing the page by modifying the properties. This is more complicated to deal with.
Some articles say to use:

$("#myTableId").dataTable( ).api().ajax.reload();
//或者
$('#myTableId').dataTable().ajax.reload();

But using it like this will report an error: DataTables warning (table id = 'myTable'): Cannot reinitialize DataTable, this is because DataTables is repeatedly initialized, and Datatables does not allow multiple initializations of the same table. Although this prompt is only for notification, it will not cause the function of the form to fail, but the pop-up box of this error prompt will pop up
insert image description here

We need to clear the original data in datatable first, and then call datatable, we need to use

$("#myTableId").dataTable().fnDestroy();

or

if($.fn.dataTable.isDataTable(myTableId)){
    
    
   var table = $(myTableId).DataTable();
   table.clear();
   table.rows.add(data).draw();
} else {
    
    
   $(myTableId).DataTable(data);
}

I tried this method and it doesn't work, and this method can't realize the function of timing refresh.
It is relatively simple to execute a certain function regularly in js, use:

//定时任务,10000代表间隔10s执行一次
setInterval(Myfunction,10000)

The current idea is:
1. First encapsulate $('#myTableId').DataTable({...}) into a function;
2. Write a function to refresh the table, and the parameters passed in are myTableId and the data source to be obtained URL, so that you can pass in the corresponding parameters when refreshing multiple tables.
3. Write a function to automatically load the table, and put the function to be refreshed in.
4. Execute the function of automatically loading the table at regular intervals.
It may be a bit troublesome to understand here. , look at the code to understand it better

2.2. Encapsulate $('#myTableId').DataTable({...}) into a function

Regions to refresh:

<div class="page-container">
    <div class="cl pd-5 bg-1 bk-gray mt-20">
        <span class="l "><strong id="total">Total</strong> </span>
        <span class="r"><span id="totalitems">Total Items:</span>
            <strong id="total-num">0</strong> </span> 
    </div>
  <div class="mt-20">
    <table id="overflow_table" class="table table-border table-bordered table-bg table-hover table-sort table-responsive">
      <thead>
      <tr class="text-c">
        <th width="40">OverflowID</th>
        <th width="100">Type</th>
        <th width="100">MailNum</th>
      </tr>
      </thead>
      <tbody>
      </tbody>
    </table>
  </div>
</div>

<div class="page-container">
<div class="cl pd-5 bg-1 bk-gray mt-20"> <span class="l"> <strong id="feedersdetail">Feeders Detail</strong></span> <span class="r"><span id="totalitems1">Total Items:</span><strong id="total-num1">0</strong> </span> </div>
<div class="mt-20">
    <table id="overflow_ind_table" class="table table-border table-bordered table-bg table-hover table-sort table-responsive">
        <thead>
        <tr class="text-c">
            <th width="40">FeedID</th>
            <th width="40">OverflowID</th>
            <th width="100">Type</th>
            <th width="100">MailNum</th>
        </tr>
        </thead>
        <tbody>
        </tbody>
    </table>
</div>
</div>

Encapsulate the dataTable that draws the table and displays the data into a function.
It needs to be displayed once when the page is loaded, and the function needs to be called once when it is initialized:

$(document).ready(function() {
    
    
		initTableConfig();
    });
function initTableConfig(){
    
    
        $('#overflow_table').dataTable({
    
    
            "aaSorting": [[0, "asc"]],//默认第几个排序
            "bStateSave": true,//状态保存
            "pading": false,
            "searching:": false,
            "lengthChange": false,
            "paging": false,
            "retrieve":true,//20230628
            "aoColumnDefs": [
                //{"bVisible": false, "aTargets": [ 3 ]} //控制列的隐藏显示
                //{"orderable":false,"aTargets":[10]}// 不参与排序的列
                {
    
     "title": th_overflowid, "targets": 0},
                {
    
     "title": th_type, "targets": 1},
                {
    
     "title": th_nummail, "targets": 2}
            ],
            "language":{
    
    url:"/globallabel/datatable_label.json"},
            "ajax": {
    
    
                url: "/show_overflowcount",
                dataSrc: ''
            },
            "initComplete": function (settings, json) {
    
    
                $('#total-num').html(json.length);
            },
            "columns": [
                {
    
    "data": "overflowid"},//id
                {
    
    
                    "data": "overflowid",
                    "render": function (data) {
    
    
                        if (data == "0") return th_goodread;//"Good Read";
                        else if (data == "1") return th_nochute;//"No Chute in Solution";
                        else if (data == "2") return th_overmax;//"Over Max Circles";
                        else if (data == "3") return th_lost;//"Lost";
                        else if (data == "4") return th_multbar;//"Multiple Barcodes";
                        else if (data == "5") return th_nodest;//"No Destination";
                        else if (data == "6") return th_ipuovertime;//"IPU Overtime";
                        else if (data == "7") return th_vcsovertime;//"VCS Operater Overtime";
                        else if (data == "8") return th_vcsqueueot;//"VCS Queue Overtime";
                        else if (data == "9") return th_vcsrejected;//"VCS Rejected";
                        else if (data == "10") return th_noread;//"NO Read";
                        else if (data == "11") return th_mesrejected;//"MES Rejected";
                        else if(data =="100") return th_all;
                        else if(data=="22") return "撤单邮件";
                        else if(data=="23") return "多次往返";
                        else return data;
                    }
                },
                {
    
    "data": "nummail"}

            ]
        });

        $('#overflow_ind_table').dataTable({
    
    
            "aaSorting": [[0, "asc"]],//默认第几个排序
            "bStateSave": true,//状态保存
            "pading": false,
            "retrieve":true,//20230628
            "destory":true,//20230628
            "aoColumnDefs": [
                //{"bVisible": false, "aTargets": [ 3 ]} //控制列的隐藏显示
                //{"orderable":false,"aTargets":[10]}// 不参与排序的列
                {
    
     "title": th_feedid, "targets": 0},
                {
    
     "title": th_overflowid, "targets": 1},
                {
    
     "title": th_type, "targets": 2},
                {
    
     "title": th_nummail, "targets": 3}
            ],

            "language":{
    
    url:"/globallabel/datatable_label.json"},
            "ajax": {
    
    
                url: "/show_overflowcount_ind",
                dataSrc: ''
            },
            "initComplete": function (settings, json) {
    
    
                $('#total-num1').html(json.length);
            },
            "columns": [

                {
    
    "data": "inductionid"},//id
                {
    
    "data": "overflowid"},
                {
    
    
                    "data": "overflowid",
                    "render": function (data) {
    
    
                        if (data == "0") return th_goodread;//"Good Read";
                        else if (data == "1") return th_nochute;//"No Chute in Solution";
                        else if (data == "2") return th_overmax;//"Over Max Circles";
                        else if (data == "3") return th_lost;//"Lost";
                        else if (data == "4") return th_multbar;//"Multiple Barcodes";
                        else if (data == "5") return th_nodest;//"No Destination";
                        else if (data == "6") return th_ipuovertime;//"IPU Overtime";
                        else if (data == "7") return th_vcsovertime;//"VCS Operater Overtime";
                        else if (data == "8") return th_vcsqueueot;//"VCS Queue Overtime";
                        else if (data == "9") return th_vcsrejected;//"VCS Rejected";
                        else if (data == "10") return th_noread;//"NO Read";
                        else if (data == "11") return th_mesrejected;//"MES Rejected";
                        else return data;
                    }
                },
                {
    
    "data": "nummail"}

            ]
        });
    }

2.3 Refresh table data function

The code is as follows (example):

    //刷新数据
    function RefreshTable(tableId, urlData){
    
    
        $.getJSON(urlData, null, function(json )
        {
    
    
            table = $(tableId).dataTable();
            oSettings = table.fnSettings();
            //table.fnClearTable(this);
            table.fnClearTable();//动态刷新
            for (var i=0; i<json.length; i++)
            {
    
    
                table.oApi._fnAddData(oSettings, json[i]);//注意取得的jason串的字符数量,要与html中列的数量要有对应
            }
            oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
            table.fnDraw();
        });
    }

2.4 Unified calls to refresh the automatic loading function of the table

    function autoLoadDataTable(){
    
    
        RefreshTable('#overflow_table','/show_overflowcount2');
        RefreshTable('#overflow_ind_table','/show_overflowcount_ind2');
    }

2.4 Execute the refresh auto-loading function at regular intervals

//间隔3s执行一次
    setInterval(autoLoadDataTable,3000);

Guess you like

Origin blog.csdn.net/sunzixiao/article/details/131477916