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 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘