2017-08-04 76 views
0

我一直在刷新我的頁面1分鐘的時間間隔,以保持數據新鮮。我需要偏離這一點,並最終獲取數據表來重新加載而不是刷新瀏覽器。重新加載數據表的時間間隔

與我的$。員額開始:

$.post('api/displayQnams.php', function(data) 
{ 
    var table = $('example1').DataTable(); 
    table.clear(); 
    table.search('').draw(); 
    var obj = JSON.parse(data); 
    obj.forEach(function(item) 
    { 
    table.row.add([item.bkgname, item.quote, item.date, item.urgent]) 
    }); 
    table.draw(); 

    setInterval(function() 
    { 
    table.draw(); 
    console.log('test'); 
    }, 10000); // 10 second interval 
}); 

上面的代碼工作正常。 DataTable打印到頁面沒有問題。

現在,在$ .post之上,我設置了DataTable。我不確定這是否是設置DataTable的最佳方式,但它確實提供了我需要的結果。

$(function() 
{ 
    $('#example1').DataTable({ 
    "dataType": "json", 
    "iDisplayLength": 25, 
    "order": [[ 6, "desc" ]], 
    "scrollY": 550, 
    "scrollX": true, 
    "bDestroy": true, 
    "stateSave": true 
    }); 
}); 

還有一些DataTable樣式,但我想保持簡短。

回到我的第一段代碼,我設置了10秒的時間間隔。我可以看到控制檯每隔10秒打印一次「測試」,但表格沒有重新加載。

我錯過了什麼讓DataTable每10秒重新加載一次?

預先感謝您。

*編輯*

下面是表看起來像什麼:

<table id="example1" class="table table-bordered table-hover table-condensed"> 
<thead> 
<tr> 
    <th>column1</th> 
    <th>column2</th> 
    <th>column3</th> 
</tr> 
</thead> 
<tbody> 
    <tr> 
    <td></td> 
    <td></td> 
    <td></td> 
    </tr> 
</tbody> 
</table> 

回答

0

而不是做這個row.add使用Ajax和定義列:在隨後

$(document).ready(function() { 
    $('#example').DataTable({ 
     "processing": true, 
     "serverSide": true, 
     "ajax": { 
      "url": "scripts/post.php", 
      "type": "POST" 
     }, 
     "columns": [ 
      { "data": "first_name" }, 
      { "data": "last_name" }, 
      { "data": "position" }, 
      { "data": "office" }, 
      { "data": "start_date" }, 
      { "data": "salary" } 
     ] 
    }); 
}); 

間隔使用:

table.ajax.reload(); 
+0

嘗試了您的建議。我得到一個「TypeError:c未定義」的錯誤,它指向datatables.min.js文件。思考? –

+0

您需要表格標題。 '' –

+0

<表ID = 「table_id的」 類= 「顯示」> 列1 列2 –

0

您在setInterval回調函數中未調用$ .post('...')。

看看你的代碼:setInterval的回調裏面,你調用 table.draw() console.log('test')

所以,你一旦讓您的數據,並僅在重繪相同的數據...

編輯:如果您檢查您的DevTools中的網絡請求標籤,您應該只注意到一個ajax請求