doutun1362 2013-04-02 23:12
浏览 44
已采纳

php / javascript - 使用ajax自动更新客户端

I am using PHP write the server side of the web page, and javascript to build the client side.

There is a div on the website that will show the data received from server side, for example, Let's say showing the current number of registered users in the databases. This number will keep changing in an unknown period of time. For example, the number could be the same in 10 hours, and it could increment by 1000 in 10 minutes.

My first question is, what is the best approach to do this functionality so that website can always show the latest or almost latest value of this data?

My original approach is using Javascript AJAX and wrapped by setInterval(1000) (-1 second) to send Ajax request to the server side. But I am not sure if this is too heavy for client side (because javascript is single threaded, it might be slow if there is a function running within each 1 second) or even server side( for example, if hundreds of users open this website and hundreds of requests will be sent to server side). So is this ok?

My second question is, if this is not a good approach, what else can I do to achieve the same goal. I was thinking about using the other way around. For example, if there is update in the server side, then use PHP in the server side to push this update to client side, or even directly change the data shown in the HTML using PHP scripting. Is this possible? if it is, is this a good approach?

Any codes or examples provided would be really appreciated.

  • 写回答

2条回答 默认 最新

  • donglin6313 2013-04-02 23:26
    关注

    You can certainly use AJAX for updates that are spread out over time, but if you want to connect to your server every second or so, I would advice against it.

    You have a couple of options here:

    • As @Kay already mentioned, long polling might be an option.

    • Alternatively, you might want to look into WebSockets or a framework that supports WebSockets, like Meteor

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

报告相同问题?

悬赏问题

  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退
  • ¥20 win系统的PYQT程序生成的数据如何放入云服务器阿里云window版?