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

报告相同问题?

悬赏问题

  • ¥30 vs2010开发 WFP(windows filtering platform)
  • ¥15 服务端控制goose报文控制块的发布问题
  • ¥15 学习指导与未来导向啊
  • ¥15 求多普勒频移瞬时表达式
  • ¥15 如果要做一个老年人平板有哪些需求
  • ¥15 k8s生产配置推荐配置及部署方案
  • ¥15 matlab提取运动物体的坐标
  • ¥15 人大金仓下载,有人知道怎么解决吗
  • ¥15 一个小问题,本人刚入门,哪位可以help
  • ¥30 python安卓开发