[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 以同步方式呈现,所以只能以这种怪异方式取得..... @_@

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