[HTML+Javascript]不同網頁視窗間傳遞參數

今天small問了我一個 AP 裡面蠻常見的功能如何寫,也就是按下一個按鈕後會開啟一個視窗,然後在視窗關閉之後將值回傳回去給原來視窗,可是這個功能要在網頁上呈現卻不太容易,如果說只要在 IE 上實作那還不太難,只要父視窗用 window.showModalDialog 開啟子網頁視窗,然後子網頁視窗只要在關閉前設定 window.returnValue,父視窗就可以接到處理結果(window.returnValue)。有於這個過程算是同步的,所以沒什麼問題。可是 firefox 基於安全理由(http://forums.mozine.org/lofiversion/index.php/t2569.html)不支援 showModalDialog,所以,目前我只知道透過 window.open 來實作,雖然不太相同,但仍然可以模擬出效果。程式如下:
parent.htm
-------------------------------------------------
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<body>
<form id = 'frmMain' name = 'frmMain'>
<button onclick = 'getValue();'>getValue</button>
<input type = 'textbox' value = "" id = 'txtValue' name = 'txtValue' style = 'display: none'/>
<button id = 'btnReturn' name = 'btnReturn' onclick = 'returnValue();' style = 'display: none'></button>
</form>
<script type = 'text/javascript'>
<!--//
var winHandler = null;
function getValue(){
winHandler = window.open("child.htm", "child");
}

function returnValue(){
alert( document.getElementById('txtValue').value );
}
//-->
</script>
</body>
</html>

child.htm
-------------------------------------------------
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<body>
<button onclick = 'btnClose_Click();'>close</button>
<input type = 'textbox' id = 'txtInput' value = ''/>
<script type = 'text/javascript'>
<!--//
var winHandler = null;
function btnClose_Click(){
if (window.opener != null){
  var txt = window.opener.document.frmMain.txtValue;  
  var btn = window.opener.document.frmMain.btnReturn;
  if (txt != null){
  txt.value = document.getElementById('txtInput').value;
  }
  btn.click();
}
self.close();
}
//-->
</script>
</body>
</html>
如果眼尖的人應該會發現我透過 btnReturn 和 txtValue 以非同步方式來取得回傳值,因為就目前所知伺服沒有其他辦法可以讓 window.open 以同步方式呈現,所以只能以這種怪異方式取得..... @_@

 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章