2017-02-21 60 views
0

我想通過一個iframe將一個php變量值傳遞給一個javascript變量。 所有文件都在我自己的服務器和域上。如何通過iframe將javascript變量傳遞給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變量值(「測試」顯示爲未定義)

+1

運行你的代碼後,它似乎工作正常?在您的php變量所在的文件中,您是否將該文件保存爲.php文件? – Option

+0

它被保存爲一個html文件,並且php是嵌入其中的。 – RealGigex

+0

所以''userOutput'是,我把它保存爲說file.php,然後JS的另一個文件我把它保存爲file2.html和所有工作正常?你能否在你的.php文件中運行'phpinfo();'。只是爲了確保PHP的設置,因爲它應該是。 – Option

回答

1

所以任何持有PHP需要進入一個PHP文件,而不是一個html的

爲例:

variableStored.php

<html> 
<head> 
    <?php 
    $userOutput = "Frrrrrrr"; 
    ?> 
</head> 
<body> 
    <p id="test123"> 
     <?php echo $userOutput; ?> 
    </p> 
</body> 
</html> 

注意:當呼應出來,它始終是最好的<?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取一切,你想讓它。

+0

謝謝!將其更改爲<?php echo xxxx?>以及。 – RealGigex

+0

完全沒問題! – Option

0

你可以echo您在JavaScript變量變量像

<script>var test = "<?= $variable ?>";</script> 

而且傳遞變量GET參數到iframe。

<script> 
     var url = "myIframe.html?var1=" + test; 
     $('#myIframe').attr('src', url"); 
</script> 

然後,您可以使用retreive

<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在這裏他的回答欄中的信息。 How to pass parameters through iframe from parent html?

+0

你在回答之前是否運行過操作代碼? – Option

+0

@Option我其實沒有。我是不是該 ? – Nicolas

+0

我會的,它對我來說很好,所以我只能假設它是在Ops本地機器上運行Ops。 – Option