jquery ajax / php轮询数据库进行更改

i am using thie jquery code to poll my database:

jQuery(function($){
  setInterval(function(){
    $.get( 'getrows.php', function(newRowCount){
      $('#rowcounter').html( newRowCount );
    });
  },5000); // 5000ms == 5 seconds
});

and display the results here:

<p>There are <span id='rowcounter'>xx</span> rows in the DB.</p>

but i am not sure what to put in the getrows.php file... does there need to be any html tags with an ID of rowcounter or newRowCount?

You're simply requesting getrows.php and expecting a response from it.

You can do anything there, as long as you echo something. Like:

<?php

     echo rand(1,10);

?>

When jQuery requests this page, PHP will generate a random number, and jQuery will append it to HTML.

Basically, you can respond anything there. jQuery doesn't care what you're responding.

Looking at that code, all the PHP file needs to do is emit a number. You'd have normal data-access code like you would anywhere else, then just:

echo $someValue;

After getting the number of rows in your database, just do:

<?php echo $rowCount; //Or whatever value you want to show ?>

That's all

jQuery intelligently guesses the type of data returned by your php script (definable in your php request's script with ContentType).

A simple php script would return HTML/Text data, so you just have to "echo" your number in your PHP script. Then your newRowCount JS value will contain your PHP-echoed number.