1

我正在制作一种监视器,它显示由另一个 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); 
    }
    ?>
4

3 回答 3

1
<script type="text/javascript">
var pollTimeout;
var observeChange = {
          'poll' : function() {
              $.ajax({
                   type: "POST",
                   url: 'checker.php',
                   data:"data=<?php echo $resultado; ?>",
                   dataType:"json",
                   async:true,
                   success:function(response){
                        // we have success fully received response,clear the timeout
                       clearTimeout(pollTimeout);                                          
                       observeChange.update(response);                             
                   },
                   error: function(XMLHttpRequest,textStatus){
                        //some error has occured please try after 5 seconds
                        pollTimeout = setTimeout(function()
                        {
                            observeChange.poll();
                        }, 1000);

                    }
                });

          },
          'update' : function(json) {
              //check whether change is there from serever or not if yes than reload page else do poll request again
              if(json.changed=="yes"){
                        window.location.reload();
              }
              else{
                observeChange.poll();
               }
          }
    };
    $(document).ready(function(){
      observeChange.poll();           
    });
    </script>

你可以通过 comet 轻松完成,不建议每 10 秒查询一次服务器,如果你使用 apache,你应该增加 apache 服务器的超时时间

建议的 apache 配置是

Timeout 300
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 240
MaxClients 150
MaxRequestsPerChild 4

检查器.php

<?
$result4 = $_POST['data'];
$response=array("changed"=>"no");
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'];
}

if ($result4==$result3){
   $response['changed']="yes"; 
}
echo json_encode($response); exit;
?>
于 2012-12-29T05:16:13.627 回答
0

您的 php 代码中缺少一些分号。我认为它根本不起作用。您应该检查回发脚本中生成的 php 错误消息。

在您的 javascript 中,您将结果与布尔值进行比较。返回的数据将是一个字符串。这是正确的方法,注意单引号。

if(data.result=='true'){ 
window.location = window.location.pathname;
}
于 2012-12-29T05:14:43.283 回答
0

checker.php中,您在转换为 JSON 格式后发送数据
在 ajax 请求中,您根本没有定义数据类型
如果 ajax 成功时的数据是 JSON,那么您必须先解析它..

        $.ajax({
               type: "GET",
               url: 'checker.php',
               data:{'ata:$resultado},
               dataType:"json",
               success:function(data){
                       if( JSON.parseQuery(data)) //this will run if the result is true.
                         {
                          window.location = window.location.pathname;
                         }            
               }
           });
于 2012-12-29T05:29:35.493 回答