我正在处理一个文件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直接访问/控制单独选项卡的唯一方法。请注意,由于同源策略,您只能对同一域中的页面执行此操作。如果您想刷新不同域上的页面,最好的方法是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>
这将导致summary.php
在您加载时在新选项卡或窗口中打开myfile.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 打开第二个选项卡,您可以将广播频道 API作为替代选项。您可以在单击按钮时从第一页发送“刷新”消息,并在第二页看到其中一条消息时自行刷新。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句