簡體   English   中英

使用 jQuery/Ajax 僅刷新表的值而不重新加載頁面

[英]Refresh only the values of a table with jQuery/Ajax without reloading the page

我一直在關注 stackoverflow 上的各種 jQuery/Ajax 線程,以在不加載整個頁面的情況下刷新表格,但是,這似乎並不能阻止表格自行重新加載。 有沒有辦法只刷新表格值,但不重繪表格?

我一直在看的資源-

如何使用 jquery/ajax 刷新 div 中的表格內容

使用ajax刷新表格內容后重繪數據表?

或多或少,我有一個getTable.php頁面顯示我的表格,沒有別的:沒有頁眉、頁腳等。

PHP (getTable.php) - 這是服務器端代碼(asp、html 等)

<?php
    echo '<table><tr><td>TEST</td></tr></table>';
?>

然后,在我的 JS 中,我使用 load() 方法刷新表格:

HTML

<div id="tableHolder"></div>

JS

<script type="text/javascript">
    $(document).ready(function(){
      refreshTable();
    });

    function refreshTable(){
        $('#tableHolder').load('getTable.php', function(){
           setTimeout(refreshTable, 10000);
        });
    }
</script>

整個表每 10 秒重新加載一次。 我知道這是因為負載,但我如何只更新值?

考慮以下示例。

 $(function() { function makeTable(data, target) { var table = $("<table>"); $("<thead>").appendTo(table); $("<tbody>").appendTo(table); // Build Header var headers = Object.keys(data[0]); $("<tr>").appendTo($("thead", table)); $.each(headers, function(i, v) { $("<th>").html(v).appendTo($("thead > tr", table)); }); // Build Body $.each(data, function(i, r) { var row = $("<tr>").appendTo($("tbody", table)); $.each(r, function(j, c) { $("<td>").html(c).appendTo(row); }); }); if (target == undefined) { return table; } else { table.appendTo(target); } } function updateTable(target, rows) { var body = $("tbody", target); var row; body.empty(); $.each(rows, function(i, r) { row = $("<tr>").appendTo(body); $.each(r, function(j, c) { $("<td>").html(c).appendTo(row); }); }); } var myTableData = [{ "fruit": "apple", "price": 1.50, "quantity": 3 }, { "fruit": "banana", "price": 0.75, "quantity": 20 }, { "fruit": "dragonfruit", "price": 3, "quantity": 1 }]; var newTableData = [{ "fruit": "apple", "price": 1.50, "quantity": 2 }, { "fruit": "banana", "price": 0.95, "quantity": 20 }, { "fruit": "grapes", "price": 2.40, "quantity": 12 }] makeTable(myTableData, "#tableHolder"); var timer = setInterval(function() { updateTable("#tableHolder", newTableData) }, 10 * 1000); });
 #tableHolder table { width: 100%; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="tableHolder"></div>

這里使用一個function根據JSON數據建表。 它提取標題並根據提供的數據構建行。 因此,您需要更新 PHP 代碼,使其更像 API,並且根據請求它可以提供 JSON 數據,而不是 HTML 數據。

第二個 function 非常相似,除了它只是擦除行並重新寫入它們。

然后我可以使用setInterval每 10 秒運行一次。

查看更多: https://www.w3schools.com/jsref/met_win_setinterval.asp

暫無
暫無

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

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