[英]how to pass php variable through iframe to javascript
我正在尝试通过iframe将php变量值传递给javascript变量。 所有文件都在我自己的服务器和域上。
这是我的html文件:
<html>
<head>
<?php
$userOutput = "bob";
?>
</head>
<body>
<p id="test123"><?=$userOutput?></p>
</body>
</html>
在我的原始页面中,我尝试访问如下信息:
<iframe id="iframeId" src="http://path/to/file.html"></iframe>
<script>
window.onload = function() {
var iframeDoc = document.getElementById('iframeId').contentWindow.document;
var test = iframeDoc.getElementById('test123').value;
console.log(test);
};
</script>
现在,我确实设法达到了我的内容,并且在尝试获得成功输入到“ file.html”中的某些输入字段的值之前,我曾尝试过,但是我似乎无法达到php变量值(“测试”显示为未定义)
因此,所有保存php的文件都需要放入.php文件而不是.html文件中
举个例子:
variableStored.php
:
<html>
<head>
<?php
$userOutput = "Frrrrrrr";
?>
</head>
<body>
<p id="test123">
<?php echo $userOutput; ?>
</p>
</body>
</html>
注意 :回显时,最好总是<?php echo 'something';?>
echo'something ;; <?php echo 'something';?>
而不是<?='something'?>
然后,让我们说iframe.html
:
<iframe id="iframeId" src="http://siteurl/variableStored.php"></iframe>
<script>
window.onload = function() {
var iframeDoc = document.getElementById('iframeId').contentWindow.document;
var test = iframeDoc.getElementById('test123').value;
console.log(test);
};
</script>
然后,您可以根据需要从variableStored.php
获取所有内容。
您可以在Javascript变量中echo
您的变量,例如
<script>var test = "<?= $variable ?>";</script>
并将变量作为GET参数传递给iframe。
<script>
var url = "myIframe.html?var1=" + test;
$('#myIframe').attr('src', url");
</script>
然后,您可以使用检索信息
<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>
我想在此感谢@Ozgur bar的回答。 如何通过父HTML通过iframe传递参数?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.