2013-01-19 67 views
0

我發現這個小腳本允許用戶在他們的網站上嵌入一個簡單的JavaScript代碼來顯示我的網站的iframe。這完美的工作,但我想通過他們嵌入的代碼,並在我的最終設置爲一個PHP變量傳遞1變量。將javascript變量通過url和解碼傳遞給一個php變量

我提前道歉我對JavaScript不太瞭解!抱歉。

示例代碼,用戶會嵌入(組件類型代碼)

<script language="JavaScript" src="http://www.mysite.com/public/iframe.js" rel='{"id":"1"}'></script> 

這是產生在我結束

// Set path to the iframe file 
var filePath = 'http://www.mysite.com/public/iframe.php'; 
// Setup the iframe target 
var iframe='<iframe id="frame" name="widget" src ="#" width="100%" height="1" 
marginheight="0" marginwidth="0" frameborder="no" scrolling="no"></iframe>'; 
// Write the iframe to the page 
document.write(iframe); 

var myIframe = parent.document.getElementById("frame"); 
// Setup the width and height 
myIframe.height = 350; 
myIframe.width = 960; 

myIframe.src = filePath; 
// set the style of the iframe 
myIframe.style.border = "1px solid #999"; 
myIframe.style.padding = "8px"; 

的最終目標是rel屬性ID的iframe代碼= 1並將其分配給一個php變量以供進一步使用。我做了很多環顧四周,似乎json_decode是答案,但似乎沒有任何工作。

回答

0

不通過id作爲rel屬性,只需將其添加到直接的網址:

<script language="JavaScript" src="http://www.mysite.com/public/iframe.js?id=1"></script> 

然後訪問它在你的PHP。

$id = (array_key_exists('id', $_GET)) ? $_GET['id'] : null; 

這是一個速記if,檢查以確保ID已經被添加到URL。這是相同的:

if(array_key_exists('id', $_GET) { 
    $id = $_GET['id']; 
} else { 
    $id = null; 
} 
0

我敢肯定rel屬性不是在iframe標記中使用的東西。這通常用於rel =「nofollow」的標籤,以便搜索引擎不會遵循該鏈接。

我還沒有嘗試過,但也許你可以在嵌入代碼中的問號後發送參數。像這樣:

<script language="JavaScript" src="http://www.mysite.com/public/iframe.js?id=1"></script> 

然後你的PHP代碼只是在GET請求中尋找。

<?php 
echo $_REQUEST['id']; 
?> 

當然,這假設您的接收腳本是用PHP編寫的。既然你顯示.js擴展名,我不確定PHP代碼是否正在執行?另外,我不是100%確定你可以在JavaScript嵌入中傳遞這樣的參數。

+0

您可以在一個用rel這可能不總是工作iframe,儘管我不確定爲什麼會這麼做 - 它通常用於微格式的各種標籤。你可以像這樣在URL中傳遞一個參數。但我打敗你:D –

+0

我試圖通過它就像你們在網址本身說的,但它不起作用。我假設問題是嵌入代碼調用一個JavaScript文件,它調用一個PHP文件,該文件是需要該變量的文件,而不是真正的.js文件。 –

0

在JavaScript中添加此找到腳本標籤本身:

var allScripts = document.getElementsByTagName('script'), 
currentScript = allScripts[allScripts.length - 1 ]; 

然後,它給你要麼使用rel屬性值或src屬性解碼。

順便說一句,當腳本元素以異步方式被加入,在這種情況下,你必須檢查src您的文件名匹配或檢查的rel也許