php - 如果数据库更改,则更新 html 数据表
问题描述
我的面板中有一个用户表,使用以下Php
代码:
<html>
<body>
<div id="order_table">
<table>
<thead>
<tr>
<th>Name</th>
<th>Mobile</th>
</tr>
</thead>
<?php
Include_once("db/connection.php");
$stmt_select_users = $conn->prepare("SELECT name,mobile FROM api_user order by create_date DESC limit 5;");
$stmt_select_users->execute();
while ($row_select_users = $stmt_select_users->fetch(PDO::FETCH_ASSOC)) {
?>
<tr>
<td><?php echo $row_select_users['name']; ?></td>
<td><?php echo $row_select_users['mobile']; ?></td>
</tr>
<?php
}
?>
</table>
</div>
</body>
</html>
我知道以下功能:
$(document).ready(function () {
setInterval(function () {
$("#order_table").load("users_table.php")
}, 3000);
});
但我不想更新整个表,只要插入一行,表就会添加该行。有什么帮助吗?
解决方案
您应该创建一个 PHP 文件,该文件只返回您想要的记录并使用 javascript 操作表。
假设您有返回 HTML 表格行元素的脚本,例如:
<tr>
<td>Some value</td>
<td>Another value</td>
</tr>
你可以做这样的事情。
$(document).ready(function () {
setInterval(function () {
$.get("my-script.php", function(data) {
$("#order_table table").append(data);
});
}, 3000);
});
有关更多信息http://api.jquery.com/append/和https://api.jquery.com/jquery.get/
我希望我能帮上忙。
编辑:代码示例
免责声明:这是一个非常简单的代码片段,您应该执行验证和优化。
<?php
// request.php
$data = [
['valor 1 - linha 1', 'valor 2 - linha 1'],
['valor 1 - linha 2', 'valor 2 - linha 2'],
['valor 1 - linha 3', 'valor 2 - linha 3'],
];
$afterIndex = $_GET['afterIndex'];
$count = sizeof($data);
$tableRows = [];
if ($afterIndex < $count) {
for ($i = $afterIndex; $i < $count; $i++) {
$item = $data[$i];
$tableRows[] = '<tr><td>' .$item[0] . '</td><td>' . $item[1] . '</td></tr>';
}
}
echo json_encode([
'index' => $count,
'rows' => $tableRows
]);
数据数组是您的数据库的模拟,根据您的需要修改代码。
<script>
document.addEventListener('DOMContentLoaded', function() {
$(document).ready(function () {
var index = 0;
setInterval(function () {
$.get("/request.php?afterIndex="+index, function(data) {
var response = JSON.parse(data);
index = response.index;
for (var i = 0; i < response.rows.length; i++) {
$("#order_table table tbody").append(response.rows[i]);
}
});
}, 3000);
});
});
</script>
上面的脚本向 php 代码发出请求并在表中呈现响应行。
该表类似于:
<div id="order_table">
<table>
<thead>
<tr>
<th>1</th>
<th>2</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
推荐阅读
- javascript - 刷新后如何保持下拉选择
- python - Python 冒泡排序仅在大数时中断
- javascript - 使用 aws-sdk 在 s3 中托管静态网站
- c# - 是否可以使用`task.Id`检查任务是否完成?
- reactjs - 无法在反应手风琴中映射对象数组
- typescript - 训练期间出现错误:新值的形状和以前的值必须匹配
- python - 有没有办法在 Python 中并行化一个循环以进行集成学习?
- python - 如何在熊猫中删除多列?
- c# - 如何从字符串中获取 lt、lg 值
- kubernetes - 为什么无法从 Kubernetes 中的另一个节点访问服务