簡體   English   中英

當我點擊按鈕時重新加載另一頁

[英]Reload another page when I click on button

我正在處理文件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>

加載myfile.php時,這將導致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打開第二個選項卡,則可以將Broadcast Channel API作為替代選項。 您可以在單擊按鈕時從第一頁發送“刷新”消息,並在第二頁看到這些消息之一時刷新自身。

您可以嘗試以下方法:

<script type="text/javascript">
    $(document).ready(function() {
        if(performance.navigation.type == 2){
 window.location.replace("www.google.com");
}

 </script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM