在不丢失折叠行的情况下更新数据库数据



对不起,我对PHP还很陌生。我有一个表格,里面装满了来自数据库的数据:

机器.php

<?php require "database.php"; // here the connection stuff
const DOT_ONLINE = "&#128994;";
const DOT_OFFLINE = "&#128308;";
?>
<table id="tableMachines" class="table table-hover">
<thead class="thead-dark">
<tr>
<th scope="col">Online</th>
<th scope="col">Name</th>
<th scope="col">Type</th>
<th scope="col">Address</th>
</tr>
</thead>
<tbody>
<?php
try {
$stmt = $db->prepare("SELECT * FROM machines ORDER BY address;");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_OBJ);
foreach ($stmt->fetchAll() as $row) {
$rowId = "row" . $row->name;
$output = "<tr data-bs-toggle='collapse' data-bs-target='#$rowId'>"
. "<td>" . ($row->online ? DOT_ONLINE : DOT_OFFLINE) . "</td>"
. "<td>" . $row->name . "</td>"
. "<td>" . $row->type . "</td>"
. "<td>" . $row->address . "</td>"
."</tr>";
echo $output;
$output = "<tr id='" . $rowId . "' class='collapse fade'>"
."<td colspan='4'>"
."<table class='table table-borderless'>"
."<tr><td>Order: " . $row->job . "</td></tr>"
."<tr><td>Length: " . $row->length . "</td></tr>"
."</table>"
."</td>"
."</tr>";
echo $output;
}
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
?>
</tbody>
</table>
<?php
$db = null;

正如您所看到的,用户可以单击每一行来显示一些进一步的详细信息。在主页中,我将上述文件放在div:中

<div id="tableMachines">
<?php require 'machines.php' ?>
</div>

定期获取新数据:

$(document).ready(function() {
setInterval(function () {
$('#tableMachines').load('machines.php');
}, 5000);
});

它工作得很好,问题是当div重新加载时,我会丢失用户显示的行。

的确,我可以跟踪哪些行被扩展,并在重新加载PHP代码后再次手动触发它们,但我认为这不是正确的方法。

你介意帮助我了解如何在不干扰UI的情况下更新数据吗?

如果是我,我会跟踪最后一个机器ID,然后在您的load((调用中发送。然后可以调用$('#tableMachines').prepend(data),而不是重新加载整个表——只重新加载最新的行。这样,您的用户选择将不受影响,但您可能需要重新绑定单击/触发器,以便新行也可以展开/隐藏。

加载machine.php之前,您可以在加载machine.php的jquery代码中创建一个名为"expanded_set"cookie。每次访问者切换时,您都可以填充cookie。在machine.php文件中,$_COOKIE['user_expandeds']可以访问您的cookie。然后,您可以自定义machine.php来处理已经切换的那些,以显示它们。

我不确定这种处理时间问题的方法,但是,您也可以通过POST类型的表单"expanded_set"发送到PHP,该表单带有一个隐藏的输入字段,该字段的名称也由jquery自动提交。您可以访问名称为$_POST['expanded_set']的已发布字段。

如果访问者不允许cookie,但不能禁止使用表单方法,则cookie方法可能会失败。

最新更新