gpt4 book ai didi

javascript - 单击按钮时重新加载另一个页面

转载 作者:行者123 更新时间:2023-12-03 00:34:42 24 4
gpt4 key购买 nike

我正在处理文件myfile.php。在这个文件中,我有以下代码:

<button type='submit' name='refresh' onclick='refresh()'></button>
<script>
function refresh(){
setTimeout(window.location.href = "summary.php",1000);
}
</script>

当我单击刷新按钮时,我的窗口位置会更新,并且浏览器会加载文件 summary.php。但是,我想留在 myfile.php 上并在第二个选项卡中刷新文件 summary.php

最佳答案

您首先必须使用 window.open 打开第二个选项卡并保存对其的引用,以便您稍后可以在单击按钮时访问它以重新加载。这是您可以直接从 JavaScript 访问/控制单独选项卡的唯一方法。请注意,由于 Same-origin policy您只能对同一域中的页面执行此操作。如果您想刷新不同域上的页面,最好在选项卡上设置 location.href

这是一个非常简单的示例,说明使用您的代码可能会是什么样子:

<button type="button" name="refresh" onclick="refresh()">Refresh</button>
<script>
let secondWindow = window.open('summary.php');
function refresh() {
secondWindow.location.reload(true); // Use true to always force reload from the server
}
</script>

当您加载 myfile.php 时,这将导致 summary.php 在新选项卡或窗口中打开。之后,您应该能够单击第一页中的刷新按钮,第二页将重新加载。

如果您不希望summary.php自动打开,您可以添加手动打开窗口的方式:

<button type="button" name="open" onclick="open()">Open</button>
<button type="button" name="refresh" onclick="refresh()">Refresh</button>
<script>
let secondWindow;

function open() {
secondWindow = window.open('summary.php');
}

function refresh() {
if (secondWindow) {
secondWindow.location.reload(true); // Use true to always force reload from the server
}
}
</script>

如果您不想依赖 JavaScript 打开第二个选项卡,您可以查看 Broadcast Channel API作为替代选择。单击按钮时,您可以从第一页发送“刷新”消息,并让第二页在看到其中一条消息时自行刷新。

关于javascript - 单击按钮时重新加载另一个页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53712244/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com