如何在PHP + Javascript/jQuery上实现观察者模式? [英] How do I implement observer pattern on PHP + Javascript/jQuery?

查看:89
本文介绍了如何在PHP + Javascript/jQuery上实现观察者模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就像在SO中回答一个问题一样,如果有人回答了这个问题,就会出现一条通知(通过AJAX吗?).我唯一重复此方法的方法是在脚本中包含一个超时,该超时在每n秒更新一次时获取.有没有办法在PHP + Javascript(带有jQuery)上使用观察者模式来做到这一点?

解决方案

您必须查看 COMET 方法.

根据维基百科

反向Ajax是指Ajax设计 使用长期HTTP的模式 连接以实现低延迟 Web服务器与 浏览器.基本上,这是一种 从客户端向服务器发送数据,以及 推送服务器数据的机制 回到浏览器.

我建议您实施以下方法,这很容易实现.我以stackoverflow回答为例.

  1. 答案页面加载完成后.发起AJAX请求(异步,因此不会阻止UI)
  2. 它将在服务器端寻找任何新更新(轮询数据库以检查是否添加了新答案)
  3. 如果有更新,则仅将数据返回给浏览器.否则要保持冷静.
  4. 将数据返回给客户端后,客户端应调用另一个AJAX请求并等待更新.
  5. 在页面余下的时间中重复第2步到第4步.

希望这会有所帮助.

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)?

解决方案

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.

这篇关于如何在PHP + Javascript/jQuery上实现观察者模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆