1

別のWebアプリケーションによって作成されたデータベースの変更を表示する一種のモニターを作成しています。変更を表示するために10秒ごとにページをリロードしていましたが、それは「方法」ではないと思います。私はいくつかの調査を行い、変更をチェックする関数を呼び出すことでajaxがそれを実行できることがわかったので、コードを書きましたが、何かが不足しているため、専門家に電話しています。主なアイデアは、ページがロードされたときに挿入されて $resultado という変数に保存された最後の行の id(number) 次に、同じクエリを実行して結果をチェックする 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>";
    ?>

checker.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>

コメット経由で簡単に実行できます。10 秒ごとにサーバーにクエリを実行することはお勧めできません。Apache を使用している場合は、Apache サーバーのタイムアウトを増やす必要があります。

推奨されるApache構成は

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

checker.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

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 に答える
0

PHPコードにいくつかのセミコロンがありません。まったく機能しないと思います。ポストバック スクリプトで生成された PHP エラー メッセージを確認する必要があります。

JavaScript では、結果をブール値と比較しています。返されるデータは文字列になります。これは正しい方法です。一重引用符に注意してください。

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