我想使用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