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 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同