簡體   English   中英

在javascript中從子窗口刷新父窗口

[英]Refresh the parent window from the child window in javascript

我找了一會兒,找不到符合我需要的答案。 我有一個頁面彈出一個窗口(window.open),記錄用戶(創建一個cookie,設置會話)然后重定向到另一個頁面。 雖然modal是重定向的,但我想刷新父頁面,所以我剛才所做的所有好東西都會被父級識別。 我試過window.opener和類似的東西。 有人可以幫我一點嗎? 謝謝

彈出window中的window.opener將引用打開窗口的window對象,所以當然你應該可以調用window.opener.location.reload(); 如果您沒有違反同源策略 ,彈出窗口可以調用腳本並操縱父窗口對象上的屬性,就像父窗口中的代碼一樣。

這是一個實例,演示了孩子回調父母的一個函數,並直接操縱父母。 以下引用了完整的代碼。

但是這個例子並沒有完全按照你所說的那樣 ,所以我也做了這個 ,它讓孩子通過window.opener.location.reload()刷新父頁面。

第一個實例的父代碼:

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Parent Window</title>
<!--[if IE]>
  <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
  article, aside, figure, footer, header, hgroup, 
  menu, nav, section { display: block; }
</style>
</head>
<body>
  <input type='button' id='btnOpen' value='Open Window'>
  <div id='display'></div>
</body>
<script type='text/javascript'>
  (function() {
    var btnOpen = document.getElementById('btnOpen');
    btnOpen.onclick = btnOpenClick;

    function btnOpenClick() {
      window.open('http://jsbin.com/ehupo4/2');
    }

    // Make the callback function available on our
    // `window` object. I'm doing this explicitly
    // here because I prefer to export any globals
    // I'm going to create explicitly, but if you
    // just declare a function in a script block
    // and *not* inside another function, that will
    // automatically become a property of `window`
    window.callback = childCallback;
    function childCallback() {
      document.getElementById('display').innerHTML =
          'Got callback from child window at ' + new Date();
    }
  })();
</script>
</html>​

(你不必像我上面那樣使用范圍界定功能,但要保持你的全局變量包含的是有用的。)

第一個實例的子代碼:

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Child Window</title>
<!--[if IE]>
  <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
  article, aside, figure, footer, header, hgroup, 
  menu, nav, section { display: block; }
</style>
</head>
<body>
  <p>I'm the child window</p>
</body>
<script type='text/javascript'>
  if (window.opener) {
    // Call the provided callback
    window.opener.callback();

    // Do something directly
    var p = window.opener.document.createElement('p');
    p.innerHTML = "I was added by the child directly.";
    window.opener.document.body.appendChild(p);
  }
</script>
</html>​

window.parent.top.location = window.parent.top.location; (或類似的東西會這樣做)

如果其他建議都不起作用(請記住在所有主流瀏覽器中測試),您也可以嘗試將父窗口的引用顯式傳遞給子窗口。 因為window.open()應該返回對子窗口的引用..所以你可以做child = window.open()然后你可以做一些像child.myParent = window這樣的事情

我通過ajax在模態中提交表單時遇到了同樣的問題,需要重新加載下面的頁面(父頁面)。 window.location.reload(); 為我工作。

暫無
暫無

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

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