iFrame:如何使用 javascript 将服务器响应 (HTML) 直接显示到 iFrame 中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15370377/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
iFrame : How to display a server response (HTML) directly into iFrame using javascript?
提问by Gendaful
I am getting a simple server response which is an html file and I want to display the same in iFrame without saving the file to my workspace or machine.
我得到一个简单的服务器响应,它是一个 html 文件,我想在 iFrame 中显示相同的内容,而不将文件保存到我的工作区或机器。
I am making an ajax call as below.
我正在按如下方式进行 ajax 调用。
Ext.Ajax.request({
url : 'url',
method : 'POST',
success : function(response) {
var responseHtmlStr =response.responseText;
Sample Server response which I am getting in responseHtmlStr is as below.
我在 responseHtmlStr 中得到的示例服务器响应如下。
<!DOCTYPE html>
<html>
<head>
<script>
function copyText()
{
alert('It is clicked');
}
</script>
</head>
<body>
Field1: <input type="text" id="field1" value="Hello World!"><br>
Field2: <input type="text" id="field2">
<br><br>
<button onclick="copyText()">Copy Text</button>
</body>
</html>
The code I am using to create the iFrame is as below.
我用来创建 iFrame 的代码如下。
;
;
As I dont want to store the server response in the server in a file. How to directly feed the server response in the iFrame?
因为我不想将服务器响应存储在服务器中的文件中。如何在 iFrame 中直接馈送服务器响应?
I tried document.getElementsByTagName('iframe')[0].contentWindow.document.write(serverResponse);?
but it is not working with the above code.
我试过了,document.getElementsByTagName('iframe')[0].contentWindow.document.write(serverResponse);?
但它不适用于上面的代码。
Any other suggestions please. Thanks in advance.
任何其他建议请。提前致谢。
Thanks Gendaful
感谢 Gendaful
回答by Diodeus - James MacFarlane
With vanilla JavaScript:
使用原生 JavaScript:
document.MyFrame.document.body.innerHTML = serverResponse
..where you have <iframe name="MyFrame"></iframe>
..你有 <iframe name="MyFrame"></iframe>
回答by SimpleSam5
Not sure if this will work, I do something similar using jquery (but could do it just as easily without)...
不确定这是否可行,我使用 jquery 做了一些类似的事情(但没有它也可以轻松做到)...
$('iframe').contents().find("html")
.append($("<head></head><body> blah blah blah </body>"));