我正在制作一种监视器,它显示由另一个 Web 应用程序创建的数据库更改,我每 10 秒重新加载一次页面以显示更改,但是,我认为这不是这样做的“方式”,所以我进行了一些研究,我发现ajax可以做到这一点,调用一个检查变化的函数,所以我写了我的代码,但是缺少一些东西,所以我打电话给专家,主要的想法是当页面加载时采取插入的最后一行的 id(number) 然后保存在一个名为 $resultado 的变量中,然后调用一个名为 check_changes 的函数,该函数执行相同的查询并检查结果,如果两个变量相等则没有变化,如果它们是不同的重新加载页面。
监视器.php
<head>
<script type="text/javascript" src="./js/prototype.js"></script>
<script type="text/javascript" src="./js/jquery-1.8.3.min.js"></script>
</head>
<?
//code that makes and print the query.
// here i check the last id(number) and saved on $resultado variable
$qry0="SELECT emergencia.id FROM emergencia ORDER BY emergencia.id DESC LIMIT 0,1";
$qry1=db_query($qry0,$conn);
while($row=$qry1->fetch_array())
{
$resultado=$row['id'];
}
//here i call check_changes every 30 seconds
echo "<script>setTimeout('check_changes()',30);";
//ajax function that check the status of database
echo "function check_changes(){
$.ajax({
type: 'POST',
data: {'data':$resultado}, //here am sending the value of result via post
url: './checker.php', //to checker.php
success: function(data) {
if(data.result==true){
window.location = window.location.pathname;
}
}
})
}";
echo "</script>";
?>
检查器.php
<?
$result4 = $_POST['data'];
include( "/home/ocelas/proyecto/include/inter_dbc_innodb.php" );
$dbc=connect_db("seguridad");
// here i check the last id(number) and saved on $result3 variable
$qry0="SELECT emergencia.id FROM emergencia ORDER BY emergencia.id DESC LIMIT 0,1";
$qry1=$dbc->query($qry0);
while($row=$qry1->fetch_array())
{
$result3=$row['id'];
}
//here i check if both are equal send false to monitor.php
if ($result4==$result3){
$result=false
echo json_encode($result);
}
else {
// a new row has been inserted, send true to monitor.php an reload page
$result=true
echo json_encode($result);
}
?>