簡體   English   中英

刷新jquery數據表而不刷新整個頁面

[英]Refresh jquery data table without refreshing the whole page

我想每 3 秒刷新一次 jquery 數據表。 我已經這樣做了,但我有分頁問題。 當我執行代碼時,分頁消失了,所以所有數據都沒有分頁顯示。

這是我的代碼:

<div id="timexx">
  <table id="example1" class="table table-bordered table-striped" style="margin-right:-10px">
    <thead>
      <tr>
        <th>id #</th>
        <th>Name</th>
      </tr>
    </thead>
    <?php
      include('../dist/includes/dbcon.php');

      $query=mysqli_query($con,"SELECT * FROM accounts_tic WHERE statuss = 'New' OR statuss = 'On-Process' order by id DESC")or die(mysqli_error());
      while($row=mysqli_fetch_array($query)){
        $id=$row['id'];
        $name=$row['name'];

        ?>
      <tr>
        <td>
          <?php echo $id;?>
        </td>
        <td>
          <?php echo $name;?>
        </td>
      </tr>

      <?php }?>
  </table>
</div>

這是我的 javascript 代碼:

$(document).ready(function() {
  setInterval(function() {
    $('#timexx').load(location.href + " #timexx>*", "")
  }, 3000);
}); 

我建議將 ajax 數據源與ajax.reload()一起使用。 事實上,我在那里鏈接的文檔頁面有一個例子說明了你所追求的。

對於您的標記,您可以簡單地創建表格和標題:

<table id="example1" class="table table-bordered table-striped" style="margin-right:-10px">
    <thead>
        <tr>
            <th>id #</th>
            <th>Name</th>
        </tr>
    </thead>
</table>

然后用 ajax 數據源初始化數據表,聲明你的列並開始循環:

$(document).ready( function () {
    var table = $('#example1').DataTable({
        "ajax" : 'http://example.com/table_data.php',
        "columns" : [
            { "data" : "id" },
            { "data" : "name" )
        ]
    });
    setInterval(function () {
        // the second argument here will prevent the pagination
        // from reseting when the table is reloaded
        table.ajax.reload( null, false );
    }, 3000);
});

現在,您需要在為 ajax 數據源http://example.com/table_data.php聲明的端點處有一個網頁,該網頁將表數據作為 json 輸出。 有幾種方法可以構建它,但我更喜歡使用data屬性作為文檔狀態:

此處顯示的數據參數格式可與簡化的 DataTables 初始化一起使用,因為 data 是 DataTables 在源數據對象中查找的默認屬性。

有了這個目標,你的 php 腳本可能看起來像這樣:

include('../dist/includes/dbcon.php');
$query = mysqli_query($con, "SELECT * FROM accounts_tic WHERE statuss = 'New' OR statuss = 'On-Process' order by id DESC") or die(mysqli_error($con));
$results = [];
while ($row=mysqli_fetch_array($query)) {
    $results['data'][] = [
        'id'   => $row['id'],
        'name' => $row['name']
    ];
}
echo json_encode($results);

旁注, mysqli_error()需要一個參數,它應該是您的連接資源。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM