jquery update page when db update
I've a page that show data inserted in a mysql db; I'd like (if it i开发者_Python百科s possible) that this view page automatically update when a record is added to the db (data are not inserted from the same page or may be inserted from another user).
thanks in advance ciao h.
First way (easiest but annoying):
Add a meta refresh to the page and the full page refreshes every x amount of time.
Second way (AJAX):
I'm assuming this is what you want.
- Load default HTML page etc... lets call it index.php
On above page create a <div> element with style display:none like this
<div id="mydata" style="display: none;"></div>
Create a PHP page that retrieves and formats the database data and prints it out in x format, i.e a table or p tags. no headers or page specific stuff just data and simple tags
On index.php put something like this
<script type="text/javascript"> function update() { $.ajax({ url: 'http://www.example.com/getData.php?q=latest', success: function(response) { $('#mydata'.html(response); } }); } // .ready function $(function() { // do setup stuff here, I think there is a refresh timer or something // that you'd use to trigger it every x amount of time // i.e something like this update(); }); </script>
EDIT: AJAX HTTP streaming forces data out to users
I know sure on the best method to do this, but and quick-and-easy solution would be to get the total number of rows in your table on page load. Then every x seconds use an AJAX script to re-check that table's row count. If it has changed you could have extra logic that then fetches the new rows.
I was thinking about this last night and realized that node.js (http://nodejs.org/) might be perfect for this if you're looking for an event driven system. There is a good tutorial on getting started using node.js at http://net.tutsplus.com/tutorials/javascript-ajax/learning-serverside-javascript-with-node-js/.
精彩评论