【问题标题】:Ajax push systemAjax推送系统
【发布时间】:2011-11-27 12:12:55
【问题描述】:

在我自己的系统中,我有一个PHP 页面,其中显示了我通过我的在线网店销售的所有商品,从最新交易到第一笔交易。

我希望这个页面在人们向我购买商品时自动更新。

我可以让AJAX5 秒调用一次来检查我数据库中的订单,但那似乎是 1980 年? 还是人们这样做?

每当我的 php newOrder() 函数(我们称之为)被调用时,我该如何推送通知到我的php 页面?

【问题讨论】:

  • 1980 年代的 Ajax 会比它的时代提前 20 年。

标签: php ajax push


【解决方案1】:

您可以通过执行以下操作来模拟推送效果(伪代码!)

// This would go on for 60-90 seconds, unless there is new data
for($i = 1; $i <= 60; $i++) {
  // Check in the database what the last timestamp is
  // Compare this to the timestamp that has been posted by the AJAX-call
  // If there is something new, show the data and then exit
  // If not, sleep for 1-3 seconds
}

你的javascript:

function pollForNewProducts() {
  // Check if there is a timestamp
  // Make an AJAX-request to the script that has the first code in it
  // If there is a response (JSON?) than evaluate that
  // If not, then run the script again
  pollForNewProducts();
}

这是一种简单而有效的方法,可以让服务器完成所有繁重的工作,而不是在客户端超时,这会导致浏览器吃掉内存。

更多信息请访问:
Simple “Long Polling” example code?
Client notification, should I use an AJAX Push or Poll?
PHP or Javascript poll code
ExtJS 3.0: Ext.Direct with PHP: Polling:ok and Pushing ?
Comet Programming: Using Ajax to Simulate Server Push

【讨论】:

    【解决方案2】:

    您可以在 PHP 中实现推送,但这不是最有效的解决方案,因为要实现推送,您需要在客户端和服务器之间保持长时间运行的连接(HTTP 或 WebSocket 连接)。

    见:

    构建实时基础设施的一般最佳实践是将推送解决方案与您的 Web 应用程序分离(注意:node.js 和 socket.io 对此进行了一些更改,但我个人仍然认为应该将其分离)。但是,假设后者仍然是您编写/托管/安装此推送解决方案所需的最佳解决方案。解耦还意味着该技术不必是 PHP,但您可以从 PHP 访问/使用它。也许有点矫枉过正?尤其是如果您的网站上没有太多用户?

    为简单起见,我建议您考虑使用 3rd 方托管服务。我在一家名为Pusher 的公司工作。使用像我们这样的服务可以让您无需安装和维护应用程序的实时部分。它还使添加您正在寻找的推送功能变得非常容易。您需要做的就是在现有应用中添加几行 PHP 代码来触发推送通知,并在前端添加几行 JavaScript。

    资源:

    如果您想研究我上面提到的替代方案或某些技术,我正在维护一个 list of realtime technologies,您可能也会感兴趣。

    【讨论】:

      【解决方案3】:

      除了关于nodejs的优秀建议..如果你还想用php来实现这个,你要寻找COMET方法,而不是ajax。

      如何在此处使用 php:http://www.zeitoun.net/articles/comet%5Fand%5Fphp/start

      【讨论】:

        猜你喜欢
        • 2012-02-26
        • 2012-05-03
        • 2019-02-05
        • 2012-03-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-11
        相关资源
        最近更新 更多