Javascript auto update page?

拥有回忆 提交于 2019-11-30 21:22:46

问题


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:

  1. have the "like" image
  2. create a script that binds a click handler to the image.
  3. once clicked, the script sends an AJAX request to the server to increment the like
  4. 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.
  5. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!