问题
Can anybody give me a direction, I want to know how to do auto updating pages like facebook have for new status updates, new likes etc. Ie., if you have a status open in a window and a user click "like", the +1 like automatically appears.
Thanks in advance.
回答1:
These are done using a PUSH model (subscribe / publish).
The client side first subscribes by issuing an AJAX request. This AJAX request stays alive indefinitely. When the server receives a new like / comment, it publishes this update to the client side thereby ending the AJAX request. The client receives this update and isntantly issues another AJAX request.
It is broadly categorized as Comet.
Once before, I had implemented a Comet web chat application and wrote a somewhat technical write up of what went into it. You can read it here, if interested.
Comet Web Chat Application
Edit:
A heartbeat mechanism (PULL model) is definitely easier to implement, but a PUSH model is far more efficient.
回答2:
You'll need to use ajax, which is a way to communicate with the database without reloading the web page : you could for example use the $ajax function of jQuery framework : here's the doc
回答3:
im not posting code, but here's a quick overview of what you might wanna do:
- have the "like" image
- create a script that binds a click handler to the image.
- once clicked, the script sends an AJAX request to the server to increment the like
- if that request succeeds, return data to the script indicating that it was a success. you might also want to return the number of likes and so on.
- once the script knows the success, have it change your "like" image.
as for counting likes, well, its up to you. for a very broad question, this is a broad answer that will point you to the right path.
来源:https://stackoverflow.com/questions/9999112/javascript-auto-update-page