使用Ajax重新加载div(Reloading a div using Ajax)

编程入门 行业动态 更新时间:2024-10-24 20:16:31
使用Ajax重新加载div(Reloading a div using Ajax)

所以我搜索了SO以帮助创建以下请求以特定间隔刷新div 。

$(document).ready(function() { $("#trigger-newsfeed").load("getNewsfeed.php"); var refreshId = setInterval(function() { $("#trigger-newsfeed").load('getNewsfeed.php'); }, 4000); });

虽然我想知道是否可以通过使用Ajax来提高效率(如果在没有我意识到的情况下它没有使用Ajax),这是有效的。

我曾尝试使用其他一些Ajax代码来完成这项工作,但是,其他解决方案会等待间隔完成然后加载数据。 因此,例如,如果间隔设置为5秒,则每次访问该页面时,用户必须等待5秒然后才会加载; 所以这是我发现最好的一个片段, 首先通过中继信息然后刷新间隔; 虽然我不确定是否最好使用jquery来做到这一点。

我问这个是因为大多数关于div刷新的在线搜索都指向了Ajax的使用。

So I searched SO to help create the following request to refresh a div at specific intervals.

$(document).ready(function() { $("#trigger-newsfeed").load("getNewsfeed.php"); var refreshId = setInterval(function() { $("#trigger-newsfeed").load('getNewsfeed.php'); }, 4000); });

This works although I was wondering if this could be made more efficient by the use of Ajax (if it is not using Ajax already without me realising).

I had tried using some other Ajax code to do this which also did work, however, other solutions would wait for the interval to finish then load the data. So for example if the interval was set to 5 seconds, each time that page is visisted, a user would have to wait for 5 seconds and then it would load; so this is the only snippet I had found worked best by relaying the information first then refreshing by the interval; although I am not sure if it is the best use of jquery to do this.

I ask this because the majority of searches made online regarding div refreshes all point to the usage of Ajax.

最满意答案

你有什么工作,但如果网络连接/计算机运行缓慢或服务器因任何原因陷入困境,请求可能会开始备份,如果这种情况发生太多,可能会导致浏览器崩溃。

要解决这个问题,请使用setTimeout而不是间隔,这样它只会在收到上一个请求的响应后4秒才会请求新数据。

function refreshNewsFeed() { $("#trigger-newsfeed").load("getNewsfeed.php",function(){ setTimeout(refreshNewsFeed,4000); }); } $(document).ready(refreshNewsFeed);

What you have will work, but if the network connection/computer is slow or the server gets bogged down for whatever reason, the requests could start to backup, and if that happens too much, it could crash the browser.

To fix that, use a setTimeout instead of an interval so that it will only request new data 4 seconds after it receives the response from the previous request.

function refreshNewsFeed() { $("#trigger-newsfeed").load("getNewsfeed.php",function(){ setTimeout(refreshNewsFeed,4000); }); } $(document).ready(refreshNewsFeed);

更多推荐

Ajax,div,使用,load,电脑培训,计算机培训,IT培训"/> <meta name="description&

本文发布于:2023-08-07 11:18:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1464215.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:加载   Ajax   Reloading   div

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!