Ajax重新加载iframe

8

如何使用jquery重新加载iframe?

<html>

<head>
<script type="text/javascript" src="jquery-1.4.2.js" > </script>


<script type="text/javascript">
//Reload Iframe Function    
</script>

</head>

<body>
    <iframe name="f1" id = "f1" src="http://www.google.com.pk/search?q=usa+current+time&ie=utf-8&oe=utf-8&aq=t&client=firefox-a&rlz=1R1GGLL_en" width=500px height=250px>
    </iframe>

<button onClick="abc()"> Reload </button>

</body>

</html>
2个回答

13
根据你对 Haim 帖子的评论,你想要的可以简化为:
$('#reload').click(function() {
    $('#f1').attr('src', $('#f1').attr('src'));
    return false;
});

或者

$('#reload').click(function() {
    $('#f1')[0].contentWindow.location.reload(true);
    return false;
});

但也许他的回答更适合您的需求。

更新:

我使用上面提供的方法组合了一个可工作的示例。我在一个页面中有一个<iframe>,它显示另一个打印时间的页面。

<iframe> HTML 代码(time.html):

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>

    The time is now <span id="time"></span>.

    <script type="text/javascript">

        $(document).ready(function() {
            $('#time').html((new Date()).toString());
        });

    </script>
</body>

还有父页面的HTML(test.html):

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>

    <iframe id="frame" src="file:///D:/Users/Cory/Desktop/time.html" width="500" height="250"></iframe>

    <button id="reload">Refresh</button>

    <script type="text/javascript">

        $(document).ready(function() {
            $('#reload').click(function() {
                $('#frame').attr('src', $('#frame').attr('src'));
                return false;
            });
        });

    </script>
</body>

在Firefox 3.6和IE 7中,这对我来说完全有效。


谢谢您的回复! 我尝试了您的代码,但不幸的是它没有起作用。<html> <head> <script type="text/javascript" src="jquery-1.4.2.js" > </script> <script type="text/javascript"> $('#reload').click(function() { $('#f1')[0].contentWindow.location.reload(true); return false; }); </script> </head> <body> <iframe name="f1" id = "f1" src="http://www.google.com.pk/search?q=usa+current+time&ie=utf-8&oe=utf-8&aq=t&client=firefox-a&rlz=1R1GGLL_en" width=500px height=250px> </iframe> <button id="reload" > 重新加载 </button> </body> </html> - Novice
你可能想将这样的大型评论作为原帖的更新发布。请查看我的回答更新,有一个可行的示例。 - Cᴏʀʏ

2
$("#reload").click(function() {
            jQuery.each($("iframe"), function() {
                $(this).attr({
                    src: $(this).attr("src")
                });
            });
            return false;
        });

这将循环遍历每个iFrame,每次单击具有class为reloadAds的链接时,并将iFrame的源设置为其自身。

这是我的代码:<body> <iframe name="f1" id = "f1" src="http://www.google.com.pk/search?q=usa+current+time&ie=utf-8&oe=utf-8&aq=t&client=firefox-a&rlz=1R1GGLL_en" width=500px height=250px> </iframe> <button id="reload" onClick="reloadFrame('f1')"> 重新加载 </button> </body> - Novice

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接