我想使用JavaScript加載iframe的內容。我不想改變src,卻直接與內容:使用innerHTML更改iframe的內容時,腳本不執行
document.getElementById('frame').contentDocument.body.innerHTML = data;
它的工作原理,但不執行的JavaScript中data
。這是安全保護還是我忘了什麼?
我想使用JavaScript加載iframe的內容。我不想改變src,卻直接與內容:使用innerHTML更改iframe的內容時,腳本不執行
document.getElementById('frame').contentDocument.body.innerHTML = data;
它的工作原理,但不執行的JavaScript中data
。這是安全保護還是我忘了什麼?
它看起來像問題不是iframe,但是當使用innerHTML插入到DOM文本中時腳本未執行。
您可能需要檢查以下堆棧溢出後的一對夫婦的解決方案:
問題是我得到一個HTML頁面,無法修改它。 – Charles 2010-02-16 13:52:25
您最好的選擇是使用jQuery等JavaScript框架來執行AJAX調用。 'jQuery.ajax()'能夠非常容易地評估JavaScript代碼。您可能想要檢查以下SO帖子以獲取更多信息:http://stackoverflow.com/questions/2203762/when-loading-an-html-page-via-ajax-will-script-tags-be-loaded – 2010-02-16 14:06:42
試試這個
在index.html頁面寫:
<script type="text/javascript">
function init()
{
var s = document.createElement("script");
s.innerHTML="alert('ops');"
document.getElementById("frame").contentDocument.getElementsByTagName("body")[0].appendChild(s);
}
window.onload = init;
</script>
...
<body>
<form id="form1">
<div>
<iframe id="frame" src="test.html"></iframe>
</div>
</form>
</body>
然後簡單的寫的test.html,如:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
</body>
</html>
從Web服務器的index.html
和負載和代碼的作品!
The問題是我從ajax獲得完整的HTML頁面。 我將從HTML中獲取一個HTML頁面到/ html,其中包含javascript .. – Charles 2010-02-16 13:50:16
但是,如果您獲得完整的網頁,則不應將其插入到body標籤中,因此應該更改frame標籤的src屬性。 – xdevel2000 2010-02-17 09:37:35
我用ajax發表帖子,並將頁面作爲響應。 – Charles 2010-02-17 10:15:18
像下面這樣的東西可以工作。
<iframe id = "testframe" onload = populateIframe(this.id);></iframe>
// The following function should be inside a script tag
function populateIframe(id) {
var text = "This is a Test"
var iframe = getObj(id);
var doc;
if(iframe.contentDocument) {
doc = iframe.contentDocument;
} else {
doc = iframe.contentWindow.document;
}
doc.body.innerHTML = text;
}
使用該用於獲取文檔跨瀏覽
//returns iframe document
function getIFrameDocument(iframe) {
var doc;
if (iframe.contentDocument) {//FF-Chrome
doc = iframe.contentDocument;
} else if (iframe.contentWindow) {
doc = iframe.contentWindow.document;
} else if (iframe.document) {//IE8
doc = iframe.document;
} else {
doc = window.frames[iframe.id].document;
}
return doc;
}
做你的代碼是直接在body元素? – xdevel2000 2010-02-16 10:47:11
你的代碼是什麼意思? – Charles 2010-02-16 13:42:56