Javascript 如何从父html通过iframe传递参数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28295870/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:34:10  来源:igfitidea点击:

How to pass parameters through iframe from parent html?

javascripthtmliframe

提问by JavaLearner

I have a html page in which I am setting the src for an iframe programmatically. How can I pass parameters through the iframe src and get them in the child html?

我有一个 html 页面,我在其中以编程方式设置 iframe 的 src。如何通过 iframe src 传递参数并在子 html 中获取它们?

Below my code:

在我的代码下面:

<iframe id="myIframe" src="" height="250px"  width="100%" scrolling="yes" frameborder="0"></iframe>

function myFunction(){
$('#myIframe').attr('src', "myIframeRequest.html"); 
}

回答by Ozgur Bar

On the main page simply pass parameters as follows

在主页面上简单地传递参数如下

function myFunction(){
$('#myIframe').attr('src', "myIframeRequest.html?param1=value1&param2=value2"); 
} 

In Iframe

在 iframe 中

You can use a script to get the desired parameter value from parameters passed to page.

您可以使用脚本从传递给页面的参数中获取所需的参数值。

<script>
function getParamValue(paramName)
{
    var url = window.location.search.substring(1); //get rid of "?" in querystring
    var qArray = url.split('&'); //get key-value pairs
    for (var i = 0; i < qArray.length; i++) 
    {
        var pArr = qArray[i].split('='); //split key and value
        if (pArr[0] == paramName) 
            return pArr[1]; //return value
    }
}
</script>

Then you can fetch the value of desired parameter like this

然后你可以像这样获取所需参数的值

var param1 = getParamValue('param1');

回答by Shobhit Sharma

If you have slightly more control on your iframe sandbox, you can try postMessageAPI to communicate with message on events you desire to trigger.

如果您对 iframe 沙箱有更多的控制,您可以尝试postMessageAPI 与您想要触发的事件的消息进行通信。

回答by Deepak David

you should make a serverside page like (myIframeRequest.php) php/jsp and get the parameter value in that page if it s an html page then parse the window.location.href through javascript and find the query/param

你应该制作一个像 (myIframeRequest.php) php/jsp 这样的服务器端页面,如果它是一个 html 页面,则在该页面中获取参数值,然后通过 javascript 解析 window.location.href 并找到查询/参数