要在PHP中动态刷新表格,通常需要结合JavaScript和AJAX。以下是一个简单的例子:
-
PHP脚本(refresh_table.php),提供数据:
<?php // 模拟数据库查询或其他数据源 $data = [ ['id' => 1, 'name' => 'Alice', 'email' => 'alice@example.com'], ['id' => 2, 'name' => 'Bob', 'email' => 'bob@example.com'] ]; // 输出JSON数据 header('Content-Type: application/json'); echo json_encode($data); ?>
-
HTML页面,包含JavaScript和AJAX来定时刷新表格:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Dynamic Table Refresh</title> <script> function fetchData() { fetch('refresh_table.php') .then(response => response.json()) .then(data => { const tableBody = document.querySelector('#data-table tbody'); tableBody.innerHTML = ''; // 清空旧的表格内容 data.forEach(row => { const newRow = tableBody.insertRow(); newRow.insertCell().textContent = row.id; newRow.insertCell().textContent = row.name; newRow.insertCell().textContent = row.email; }); }) .catch(error => console.error('Unable to get data.', error)); } // 设置定时器每隔一定时间刷新表格 setInterval(fetchData, 5000); // 每5秒刷新一次 </script> </head> <body> <table id="data-table"> <thead> <tr> <th>ID</th> <th>Name</th> <th>Email</th> </tr> </thead> <tbody> <!-- 表格内容将通过JavaScript动态填充 --> </tbody> </table> </body> </html>
在这个例子中,当页面加载时,JavaScript 会设置一个定时器,每5秒钟触发一次
fetchData
函数。这个函数通过 AJAX 请求refresh_table.php
,获取最新的数据,然后使用这些数据更新HTML表格。这样,表格就会动态地按照后端数据的更新进行刷新。