用于实时更新的jQuery框架刷新

时间:2012-01-24 15:22:39

标签: jquery iframe refresh updates

我想处理一些在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>

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

2 个答案:

答案 0 :(得分:2)

<!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>

答案 1 :(得分:1)

你试图通过轮询来实现你的目标,这是一种不好的做法,如果可能的话,最好避免它并使用推动。轮询意味着继续要求资源,直到它可用。推送意味着资源本身会在可用时立即告诉您。

在这种情况下,您可以使用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>
});