jQuery AJAX call function on timeout

2019-07-26 02:48发布

问题:

I am trying to reload my jQuery DataTables without refreshing the page in an attempt to capture new data.

Here is my initial ready function that begins the process:

 $(document).ready(function()
 {
   $.ajax({
     url:'api/qnams_all.php',
     type:"GET",
     dataType:"json"
   }).done(function(response) {
       console.log(response.data);
       renderDataTable(response.data)
   }).fail(function() {
       alert( "error" );
   }).always(function() {
       alert( "complete" );
   });  
 });

I'm sending the data to this function:

 function renderDataTable(data)
 {
   var $dataTable = $('#example1').DataTable({
     "data": data,
     "iDisplayLength": 25,
     "order": [[ 6, "desc" ]],
     "bDestroy": true,
     "stateSave": true
     // there's some more stuff, but I don't think necessary to show
   });
 }

I'm trying to utilize the answer found here: How to refresh table contents in div using jquery/ajax

As follows:

 setTimeout(function(){
   $( "#example1" ).load( "mywebpage.php #example1" );
 }, 2000);

Using all of the above code, when the page first loads, it looks like this:

But after the refresh, it looks like this:

The picture immediately above does indeed reload without the page refreshing, but I'm not sure why it looks like the picture above.

回答1:

I think this example will be usefull

//Reload the table data every 30 seconds (paging reset)
var table = $('#example').DataTable( {
    ajax: "data.json"
} );

setInterval( function () {
    table.ajax.reload();
}, 30000 );

more details - here



回答2:

Create a function to load/render data then call it in document ready and after 2 seconds:

function loadAndRender()
{
    $.ajax(
    {
        url:'api/qnams_all.php',
        type:"GET",
        dataType:"json"
    }).done(function(response)
    {
        console.log(response.data);
        renderDataTable(response.data)
    }).fail(function()
    {
        alert( "error" );
    }).always(function()
    {
        alert( "complete" );
    });  

}

function renderDataTable(data)
{
    var $dataTable = $('#example1').DataTable(
    {
        "data": data,
        "iDisplayLength": 25,
        "order": [[ 6, "desc" ]],
        "bDestroy": true,
        "stateSave": true
        // there's some more stuff, but I don't think necessary to show
    });
}

$(document).ready(loadAndRender);

setTimeout(loadAndRender, 2000);