【问题标题】:jQuery Frame Refresh for Live Updates用于实时更新的 jQuery 帧刷新
【发布时间】:2012-02-17 20:19:56
【问题描述】:

我想处理一些在 iframe 中呈现的实时更新。这个名为 disp.php 的文件在数据库中查询一个表“posts”并从下到上显示它们。现在,当新条目添加到“帖子”时,我希望它能够实时反映。

我可以使用

<meta http-equiv="refresh" content="10" />  

在 disp.php 中。但是持续的清爽感觉还是很烦人。现在我正在尝试以这种方式实现刷新,这是行不通的。

<!DOCTYPE html> 
<html>
<head>
<title>Live Updates</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js">
</script>
<script> 
function refreshLiveFrame() {
$('body', window.frames['myliveframe'].document).loadIfModified("disp.php");
setTimeout("refreshLiveFrame()", 1000);
}
$(document).ready(function() {
refreshConsole();
});
</script> 
</head>
<body>
<iframe name="myliveframe" src="disp.php">
</iframe>
</body>
</html>

我需要一种实时异步刷新的方法。有人有解决方法吗?谢谢。

【问题讨论】:

    标签: jquery iframe refresh updates


    【解决方案1】:
    <!DOCTYPE html> 
    <html>
        <head>
        <title>Live Updates</title>
            <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
            <script type="text/javascript">
                $(document).ready(function()
                {
                    refresh(); // Calling refresh() on document ready
                    window.setInterval("refresh()", 10000); // Calling refresh() every 10 seconds
                });
    
                function refresh()
                {
                    // Asynchonously requesting the content of disp.php
                    $.get('disp.php', function(data)
                    {
                        // This will be executed when you get the response back from the server
                        $('#posts').html(data);
                    });
                }
            </script> 
        </head>
        <body>
            <div id="posts"></div>
        </body>
    </html>
    

    【讨论】:

      【解决方案2】:

      您正在尝试使用轮询来实现您的目标,这是一种不好的做法,并且在可能的情况下,最好避免它并使用推送来代替。轮询意味着继续不断地请求资源,直到它可用。推送意味着资源本身会在可用时立即通知您。

      在这种情况下,您可以像这样使用 jQuery 来使用推送:

      $('iframe[name=myliveframe]').load(function()
      {
          // This will be called every time the page inside the iframe has finished loading
          // $(this).contents() contains the page HTML
          // Use $(this).contents().find('body').html() if you want to read the content of the <body>
      });
      

      【讨论】:

      • 我刚刚删除了 iframe。而是使用 div 加载该 div 中另一个页面的内容。 var auto_refresh = setInterval( function() { $('#mydiv').load('disp.php'); }, 10000);
      • 当然。 :(。但是现在这对我有用。而且我无法获取您的代码。如果每次加载 iframe 内的页面时都执行该函数,我该如何使用它?假设, iframe 最初加载页面,然后调用该函数。在其中我读取 iframe 的 HTML 内容。我能用它做什么?检查更改?到底如何推送?帮帮我。
      • 我错误地理解了你的问题,我添加了另一个答案,应该可以解决你的问题。仍在使用轮询,但至少用户不会注意到它:) 我没有任何在这种情况下使用推送的经验,但我会给你一个关键字:彗星
      猜你喜欢
      • 2023-03-24
      • 2012-05-28
      • 2011-10-22
      • 1970-01-01
      • 1970-01-01
      • 2012-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多