开发者

Using AJAX for an auto-updating page containing values from a database?

Can someone explain how to create a .php page which auto-updates with values from a database? Would using AJAX be best for something like this?开发者_如何转开发 I want this PHP code, but I want the page to be updated whenever 'values01' is added to or changed, without having to refresh the page.

$query = "SELECT values01 FROM users WHERE username='$username'";

$result = mysql_query($query);

while($row = mysql_fetch_array($result, MYSQL_ASSOC))

{

echo nl2br("{$row['values01']}");

}

Any help would be appreciated! :)


What you are describing would be a push notification from the web server. Unfortunately, I have not found a reliable way to do a traditional push, where the web server would initiate the connection with the client (from my limited research, it appears that there were proposals for the http standard to support push, however, it doesn't look like a widely adopted standard ever emerged). However, this can be done in a bit more roundabout way.

There is a way around the push limitation that is typically used:

  1. Browser connects to the page, loads up the current "state" of the database. A session variable (lets call it $_SESSION['currentState']) is saved with the starting state of the database. A javascript timer on the client's browser starts ticking down (lets just say that timer is 10 seconds long).
  2. Once the timer expires, an AJAX call is made to a script on the server. Lets call that script "updateValues.php". updateValues.php checks the new state of the database. If the database differs from $_SESSION['currentState'], we return whatever changes have been made, in some nice form (json, xml, etc..), and update $_SESSION['currentState'] with the new state. If there was no change, we reply with something to that extent.
  3. Upon receiving the data, the browser executes some javascript that then updates the rendering in the browser if changes have been made to the db, and then restarts the timer.
  4. goto 2.

The only thing you are missing here from a typical push notification, is the 10-second (or whatever you choose for your timer) lag.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜