问题
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.
- After the answer page load complete. Initiate a AJAX request (Asynchronos, so it wont block the UI)
- And it will look for any new updates on the server side (polling the DB to check if any new answers added)
- And return the data only to browser, if there is an update. otherwise stay calm.
- After returning the data to client, client should invoke the another AJAX request and wait for the updates.
- 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