繁体   English   中英

如何使用window.open将参数从父窗口传递到子窗口

[英]How to pass a parameter to the child window from parent window using window.open

如何使用window.open将参数从Java脚本中的父窗口传递到子窗口。

请给我任何想法。

您可以使用查询字符串来传递参数,这是一种更好的方法。

关于您使用window.open传递参数的要求。 您可以访问一些元素和全局变量,但其中的值无法保留。 例如:当您执行以下代码时

popupWindow = window.open(url,'popUpWindow','height=500,width=500'); 
popupWindow.alert("test");

您会在打开新窗口时看到警报。 但是仅在该警报之后才加载数据。 因此,即使您能够在子javascript中设置任何全局变量的值,但也无法保留该值,因为打开窗口后页面会加载,因此数据会刷新。

当您为子窗口创建html时,请在html中创建一个隐藏字段并进入子窗口。

什么样的参数? 我的意思是,参数是什么? 例如,您可以在url中添加一个GET值:

window.open("http://example.com/script.php?KEY=value")

然后,您将在PHP中的$ _GET ['KEY']中包含该“值”

将值作为查询字符串传递

尝试以下

window.open("url.php?param=value&param2=value2");

我最初尝试过:

父窗口:

 var parms = {arg1: "arg1", arg2:"arg2"};
 var handle = window.open(url);
 // stringifyed to make sure the child window does 
 //not try to access object by reference from child to parent.
 handle.window.parameters = JSON.stringify(parms);

子窗口:

$(document).ready(function(){
    var args = JSON.parse( window.parameters);
    // and so on.
});

问题在于该值有时是在子窗口准备好之前设置的,因此当子窗口准备好时,它将是不确定的。

因此,我改为使用sessionStorage(注意:这将无法跨域工作。)

家长:

// the user can cause more than one child window so I give storage a unique id.
var parms = JSON.stringify({arg1: "arg1", arg2:"arg2"});
var storageId = "parms" + String(Date.now());
sessionStorage.setItem(storageId, parms);
window.open(url + "?sid=" + storageId);

这对孩子:

$(document).ready(function(){
    var prmstr = window.location.search.split("=");
    var sid = prmstr[1];
    var args = JSON.parse(sessionStorage.getItem(sid));
    sessionStorage.removeItem(sid);
    // and so on
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM