2015-01-07 18 views
2

我知道這已經被問了很多次,但每個人都要求它適合自己的需求,從而無法找到答案,幫助我設定值

我有兩個網站,並獲得雙方並可以添加任何我需要這兩個網站內

我對這個網站的第一個站點

http://www.mysite1.com

我有特定值的文本字段 我有一個iFrame,其內容來源於我的其他網站。

<input type='text' name='test1' value='5'> 
<iframe name='myframe' src='http://www.mysite2.com/index.php'></iframe> 
此頁面上

http://www.mysite2.com/index.php

我有輸入文本字段

我想實現的是:

正從我的第一個站點的具體數值輸入字段在我的第二個網站

+0

如果這兩個網站位於不同的域名中,您必須使用[Window.postMessage](https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad = RJA&uact = 8&VED = 0CB0QFjAA&URL = HTTPS%3A%2F%2Fdeveloper.mozilla.org%2Fen-US%2Fdocs%2FWeb%2FAPI%2FWindow.postMessage&EI = d42tVIDoC4b4yQSU_YLQCA&USG = AFQjCNEnazVAnZe__qabZI2Vcu1R9u8b0g&SIG2 = oSaANLF7G504jbK2667cfA)。 – JCOC611

+0

您是否嘗試用站點2中的數據設置站點1上的輸入字段? –

+0

試圖設置站點2的輸入字段與從站點1拉的數據 – JackNew

回答

1

由於操作具有不同來源的幀會導致發生跨源錯誤,因此您必須使用window.postMessage()方法將消息發送給子代,並在其中收聽window.onmessage並處理消息。

下面是一個例子,假設你有一個DOM結構是這樣的:

  • 網站#1(www.mysite1.com):

    <body> 
        <iframe id="site2-frame" src="http://www.mysite2.com/index.php"></iframe> 
    </body> 
    
  • 站點#2(WWW .mysite2.com)在iframe:

    <body> 
        <input id="input-field" /> 
    </body> 
    

然後在您的網站#1,你必須將消息發送到框架上,像這樣:

var frame = document.getElementById('site2-frame'); 

frame.contentWindow.postMessage('Something something something', '*'); 

而且在您的網站#2,框架中的一個,你會聽消息,設置數據:

var input = document.getElementById('input-field'); 

window.addEventListener('message', function(e) { 
    // Check the origin, accept messages only if they are from YOUR site! 
    if (/^http\:\/\/www\.mysite1\.com/.test(e.origin)) { 
     input.value = e.data; 
     // This will be 'Something something something' 
    } 
}); 
1

JCOC611是對的。在現代Web開發Window.postMessage是要走的路。選擇iframe中的元素並更改它們的值很可能會導致跨源安全性錯誤 - 這是出於很好的原因。

下面是一個例子,你怎麼可以跨網站/ iframe中使用的postMessage事件模式實現交換價值:

<script> 
window.onload = function(){ 

    // Define the target 
    var win = document.getElementById('iframe').contentWindow; 

    // Define the event trigger 
    document.getElementById('form').onsubmit = function(e){ 

     // Define source value or message 
     win.postMessage(document.getElementById('source').value); 
     e.preventDefault(); 
    }; 
}; 
</script> 

<form id='form'> 
    <input id="source" type='text' value='5'> 
    <input type='submit'/> 
</form> 


<iframe name='myframe' src='http://www.mysite2.com/index.php'> 

    <!-- This is what happens inside the iframe --> 
    <form id='form'> 
     <input id='target' type='text' value=''> 
    </form> 

    <script> 

     // Wait for the message 
     document.addEventListener('message', function(e){ 

      // When you receive the message, add it to the target 
      document.getElementById('target').textContent = e.data; 
     }, false); 
    </script> 

</iframe> 
+0

我認爲Window.postMessage是要走的路,但試過你的方式它沒有工作,當我按提交沒有發生除了/?得到添加到我的網站的網址 – JackNew

0

可以使用iframe網址查詢字符串名稱值對總是發送瓦爾,然後在頁面加載會根據需要填充變量或輸入字段。