问题
I have a Ruby script which is constantly updating a MySQL database. I want to show the "mysql_num_rows()
" in realtime. So as an entry is entered into the database by the Ruby script I want the PHP script to update its mysql_num_row() count in realtime.
I tried using <meta http-equiv="refresh" content="5">
, but I don't think this is the best solution.
Does any one have a better solution?
回答1:
Use JavaScript on the page to periodically make a call to the server and get some data. Using the jQuery library for cross-browser support of AJAX, you would simply do this:
jQuery(function($){
setInterval(function(){
$.get( '/getrows.php', function(newRowCount){
$('#rowcounter').html( newRowCount );
});
},5000); // 5000ms == 5 seconds
});
That will make a request to your server every 5 seconds and stick the result of whatever you send back into an element with an id of rowcounter
, e.g.
<p>There are <span id='rowcounter'>xx</span> rows in the DB.</p>
回答2:
I would use an ajax updater to keep polling a page that prints your mysql_num_row(). Prototype would be a good solution: http://www.prototypejs.org/api/ajax/updater
回答3:
With only PHP and javascript the only way is to continually check for updates, though wajiw is correct that the ajax route would be less intrusive/noisy than a full page refresh.
It would take an application (or applet) with a standing connection on a port/socket to get updates as they come.
回答4:
If you are going to have large number of visitors, it's better to store your rows number into static file with separate script run by cron (or run your script in endless loop on server). Then show number from this static file with JS, like Phrogz suggested. Otherwise you can exceed mysql connections limit very quickly.
回答5:
Polling can never be realtime!
However Juggernaut looks like it meets your requirments: http://juggernaut.rubyforge.org here
But you will need flash on the client side.
来源:https://stackoverflow.com/questions/4200515/how-do-i-do-realtime-database-polling-in-mysql-php