如何在更新数据库时刷新页面? [英] How can I refresh a page when a database is updated?

查看:434
本文介绍了如何在更新数据库时刷新页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检测对数据库所做的最新更新,并在发生更改时静默地刷新页面?

How can I detect the latest updates made to a database and silently refresh a page when a change occurs?

我们假设数据库访问如下:

Let's say the database access looks like:

$host = "localhost";
$username = "root";
$password = "root";
$db = mysql_connect($host,$username,$password) or die(mysql_error());
mysql_select_db('ccr') or die(mysql_error());

任何想法和样品将不胜感激。谢谢。

Any ideas and samples would be appreciated. Thank you.

推荐答案

这是我最近使用jQuery实现解决方案。

This is how I recently implemented a solution using jQuery.

每次发生重大更新时,PHP都会在数据库中增加一个字段。

PHP increments a field in the database every time a significant update occurs.

<?php

//  Call this function when data changes
function update_clients()
{
    mysql_query( "UPDATE pageGen SET id = id + 1 LIMIT 1" );
}

//  Call this function to get the ID to pass to JavaScript
function get_update()
{
    $result = mysql_query( "SELECT id FROM pageGen LIMIT 1" );
    $update = mysql_result( $result, 0, 'id' );
    return $update;
}

?>

当页面初始加载时,从数据库中填充一个JavaScript变量:

When the page is initially loaded, populate a JavaScript variable with a number from the database:

<script type="text/javascript">
var pageGenID = 25218603  //  generated by PHP
var processUpdate = function( response ) 
{
    if ( pageGenID < response ) 
    {
        replace_current_data_with_new_via_ajax();
        pageGenID = response;
    }
}
//  Compare our Page Generate ID against that of the server
var checkUpdates = function()
{
    serverPoll = setInterval( function()
    {
        $.get('script_to_return_latest_pageGenID.php', 
          { lastupdate: 1 }, 
          processUpdate, 'html');
    }, 10000 )
};

//  Check for updates every 10 seconds
$( document ).ready( checkUpdates );

</script>

这篇关于如何在更新数据库时刷新页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆