【问题标题】:How to pass a parameter to the child window from parent window using window.open如何使用window.open将参数从父窗口传递给子窗口
【发布时间】:2014-03-12 05:30:26
【问题描述】:

如何在 Java Script 中使用 window.open 将参数从父窗口传递给子窗口。

请给我任何想法。

【问题讨论】:

  • 您可以将其作为 url(查询字符串)的一部分传递。
  • 我只是在没有传递参数的情况下尝试。但我想通过使用 window open 来传递参数。怎么做 。你能给我任何想法吗? popupWindow = window.open(url,'popUpWindow','height=500,width=500,left=100,top=100,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories =no, status=yes');
  • 请在您的 url 示例中添加参数作为查询字符串:url="test.php?param1=value1&param2=value2"

标签: javascript


【解决方案1】:

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

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

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

当新窗口打开时,您会看到一条警报。但数据只会在该警报之后加载。因此,即使您可以在子 javascript 中设置任何全局变量的值,但由于页面在打开窗口后加载,因此无法保留该值,因此数据会被刷新。

【讨论】:

    【解决方案2】:

    我最初尝试过这个:

    父窗口:

     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
    });
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

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

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

        然后你会在你的(在 PHP 中)$_GET['KEY'] 这个'值'

        【讨论】:

          【解决方案5】:

          将值作为查询字符串传递

          尝试关注

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

          【讨论】:

            猜你喜欢
            • 2010-12-16
            • 1970-01-01
            • 2015-11-13
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-05-13
            • 1970-01-01
            • 2019-01-31
            相关资源
            最近更新 更多