douhe1002 2009-10-27 07:05
浏览 33
已采纳

如何在PHP + Javascript / jQuery上实现观察者模式?

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

  • 写回答

2条回答 默认 最新

  • duanpu8830 2009-10-27 07:55
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler