2013-12-21 46 views
1

我有這樣的代碼工作的罰款與本地文件:的getElementById( 「」)與網上IFRAME SRC

<html> 
<body> 
<iframe id="frame1" name="frame1" frameborder=0 src="form.html" width=100% height=70%></iframe> 
</body> 
<script type='text/javascript'> 
    window.onload= function(){ 
     var iframe = document.getElementById('frame1'); 
     var innerDoc = iframe.contentDocument || iframe.contentWindow.document; 
     var input = innerDoc.getElementsByName('input1')[0].value; 
     alert(input); 
    } 
</script> 
</html> 

form.html:

<input name="input1" type="text" value="testing"/> 

一切OK,但是當我改變IFRAME的src:

<iframe id="frame1" name="frame1" frameborder=0 src="form.html" width=100% height=70%></iframe> 

有了:

<iframe id="frame1" name="frame1" frameborder=0 src="http://test.hklearningmap.com/form.html" width=100% height=70%></iframe> 

它不工作。我怎樣才能使它的工作沒有上傳本地文件到form.html相同的位置?謝謝。

回答

0

只有因爲您將其加載到iframe中,才能使用js訪問遠程html內容。閱讀關於同一來源政策。

1

您正遇到瀏覽器強加的Same Origin Policy。源A的窗口中運行的JavaScript代碼無法從源B訪問窗口(框架)中的文檔。

有一些例外,例如兩個文檔都將相同的值分配給document.domain。但是可以設置的值有一些限制(鬆散地說,你只能設置一個超級域名,例如你可以從www.example.com加載的頁面設置example.com),當然這兩個文件都必須設置它(因爲這種合作是告訴瀏覽器可以允許跨源腳本)。