Code outline for auto-update pages
I want to mess around with realtime information, and there is a pretty standard functiona开发者_StackOverflow中文版lity that I want to duplicate:
It occurs here on SO when you're on a single-question view, typing your answer, and an alert pops up top saying "there are 3 news answers, click to show"
It also occurs on Twitter "There are 5 new tweets in this search: click to update"
I'm pretty versed in server and client side code, and what I'm looking for is the basic outline (not even psuedo code, but perhaps plain english) of how something like this happens.
Is there a CRON job on the server running every minute, that shoots a signal to a long-polled AJAX bit on the page?
Does the page itself poll a server?
Any and all solutions are welcome. Thanks!
You can implement that using an AJAX call that runs on the client side at a regular interval using the Javascript setTimeout
method. You'll have a Javascript function that calls your server side method that checks if an update has occurred, displays any update, then calls setTimeout to call itself.
pseudo code:
function updateCheck()
{
//make ajax call
//do something if any update has occurred
setTimeout("updateCheck()", 10000); //second param is in milliseconds
}
From the top of my head, I'd make it via javascript - setting timeouts to question the server. That's only an educated guess though.
Looks like SO uses a periodical updater to make an ajax request to a url like:
https://stackoverflow.com/posts/2307584/answer-activity-heartbeat
This returns a JSON result:
{"Result":false,"Count":0}
Heres an example of the result when a new answer exists:
{"Result":true,"Count":1}
精彩评论