Auto refresh DataTables table with reloading the w

2019-04-16 17:33发布

问题:

Is anyone able to guide on how to refresh datatables datas in every 1min interval without reloading the entire page.

This is my code:

$(document).ready( function () {
           var refreshTable = $('#id_css').DataTable({
                "sAjaxSource": 'ajax/alert_data.txt',
                "bServerSide": true,
                "iDisplayLength": 100,
                "bFilter": false,
                "aaSorting" : [[2, "desc"]],
                "fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
                    if ( aData[2] == "5" )
                    {
                        $('td', nRow).css('background-color', 'Red');
                    }
                    else if ( aData[2] == "4" )
                    {
                        $('td', nRow).css('background-color', 'Orange');
                    }
                 }

              });
setInterval (function test() {
refreshTable.fnDraw();
}, 1000);
 });

I have tried using this plugin fnReloadAjax.js but keep getting TypeError: refreshTable.fnReloadAjax is not a function. This is how I used it:

setInterval (function test() {
refreshTable.fnReloadAjax();
}, 1000);

and i have also added its cdn

<script src="//cdn.datatables.net/plug-ins/725b2a2115b/api/fnReloadAjax.js"></script>

Any assistance or guide will be much appreciated.

回答1:

You could do

var refreshTable = $('#id_css').DataTable({ ...

Then within the document.ready function (has to be in the scope otherwise fnDraw won't work) you use:

setInterval (function test() {
    refreshTable.fnDraw();
}, 1000);

There is a scope issue, the code should look like this:

$(document).ready( function () {
       var refreshTable = $('#id_css').DataTable({
            "sAjaxSource": 'ajax/alert_data.txt',
            "bServerSide": true,
            "iDisplayLength": 100,
            "bFilter": false,
            "aaSorting" : [[2, "desc"]],
            "fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
                if ( aData[2] == "5" )
                {
                    $('td', nRow).css('background-color', 'Red');
                }
                else if ( aData[2] == "4" )
                {
                    $('td', nRow).css('background-color', 'Orange');
                }
             }   
       });
       setInterval (function test() {
         refreshTable.fnDraw();
       }, 1000);
 });


回答2:

Its strange that changing the DataTable to dataTable was the root cause of this failing the whole time. That is small d instead of capital D, really annoying...

$(document).ready( function () {
       var refreshTable = $('#id_css').dataTable({
            "sAjaxSource": 'ajax/alert_data.txt',