如何检测对数据库所做的最新更新,并在发生更改时以静默方式刷新页面?
假设数据库访问如下:
$host = "localhost";
$username = "root";
$password = "root";
$db = mysql_connect($host,$username,$password) or die(mysql_error());
mysql_select_db('ccr') or die(mysql_error());
任何想法和样品将不胜感激.谢谢.
解决方法:
这就是我最近使用jQuery实现解决方案的方式.
每次发生重大更新时,PHP都会增加数据库中的字段.
<?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变量:
<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>