gpt4 book ai didi

javascript - 检查数据库是否有更改,然后重新加载页面

转载 作者:行者123 更新时间:2023-11-30 08:25:11 26 4
gpt4 key购买 nike

我正在开发一个脚本,我需要它来检查数据库中的更改。

每次执行 edit.php 时,它都会生成一个时间戳并将其保存在数据库中。如果数据库中保存了较新的时间戳,则需要刷新 edit.php 页面。

因此,我创建了一个页面,显示数据库中保存的当前时间戳 (checkupdates.php),并使用 JS 脚本检查该页面并比较时间戳。如果DB较新,则需要刷新页面。

我没有 javascript 的概念,到目前为止我的页面对当前脚本没有响应。

这是我到目前为止得到的:

编辑.php

<?php 
$date = new DateTime();
$utime = $date->getTimestamp(); //GET TIMESTAMP ON PAGE LOAD

updatetimestampondb($id, $utime); //UPDATE DB WITH CURRENT TIMESTAMP
?>


<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

<script type="text/javascript">

var updatetime = "<?php echo $utime; ?>"; //The timestamp saved in the DB when the page is executed

function checkUpdate() {
$.ajax({
url: 'checkupdates.php?id=$id',
timeout: 2000,
success: function(data) {
if (currentTS < updatetime) {
alert('The page will be reaload');
location.reload();
}
});
}

setInterval(checkUpdate, 5000);

</script>

checkupdates.php

<?php
(...) //Check DB Script for actual timestamp saved
echo "<script>var currentTS = ".$sheet->utime.";</script>";
(...)
?>

谢谢!

最佳答案

您最好在 ajax 中发送 json 响应,因为 js 代码将无法正常工作,请尝试以下操作:

 $response = ["currentTS" => $sheet->utime];
echo json_encode($response);

并像下面这样编写你的ajax(如果$id是一个php var,请将其写为<?=$id?>):

function checkUpdate() {
$.ajax({
url: 'checkupdates.php?id=$id',
timeout: 2000,
dataType: 'json',
success: function(data) {
if (data.currentTS < updatetime) {
alert('The page will be reaload');
location.reload();
}
});

关于javascript - 检查数据库是否有更改,然后重新加载页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46879278/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com