How do I implement observer pattern on PHP + Javascript/jQuery?

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-11 04:42:30

问题


Just like in SO, where one is answering a question, if somebody has answered said question, a notification will appear (via AJAX?). My only way of somewhat replicating this is by including a timeout on my script that fetches if there is an update every n seconds. Is there a way to do this using observer pattern on PHP + Javascript (w/ jQuery)?


回答1:


you have to look at the ReverseAJAX or COMET methodologies.

As per wikipedia

Reverse Ajax refers to an Ajax design pattern that uses long-lived HTTP connections to enable low-latency communication between a web server and a browser. Basically it is a way of sending data from client to server and a mechanism for pushing server data back to the browser.

EDIT:

i suggest you to implement the following approach, this is simple to implement. I take stackoverflow answering as an example.

  1. After the answer page load complete. Initiate a AJAX request (Asynchronos, so it wont block the UI)
  2. And it will look for any new updates on the server side (polling the DB to check if any new answers added)
  3. And return the data only to browser, if there is an update. otherwise stay calm.
  4. After returning the data to client, client should invoke the another AJAX request and wait for the updates.
  5. Repeat step 2 to 4 for the rest of the page life time.

Hope this helps.




回答2:


If you use timeouts to query the server for updates, it may still be considered a peculiar implementation of the Observer pattern. Unfortunately, it's not possible to do it the other way around. If the server finishes responding to the main HTTP request, the client just finishes "listening" to it. The only way to do this is to make an asynchronous request from the client.



来源:https://stackoverflow.com/questions/1629149/how-do-i-implement-observer-pattern-on-php-javascript-jquery

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