通过javascript(书签):我需要创建一个iframe,然后向其中添加一个表单,然后再提交一个提交表单的脚本。

以下内容适用于Chrome,但不适用于IE:

var i = document.createElement('iframe'); // also give it id = iframe_id
var frm = document.createElement('form');  // also add inputs and values
var s = document.createElement('script'); // also add innerHTML that submits form

document.body.appendChild(i);
window.frames['iframe_id'].document.getElementsByTagName('body')[0].appendChild(frm);
window.frames['iframe_id'].document.getElementsByTagName('body')[0].appendChild(s);

在IE中,我收到一个错误:无法获取未定义或空引用的属性'appendChild'

在将iframe添加到文档之前,我尝试将表单和脚本附加到iframe:
 i.appendChild(frm);
 i.appendChild(s);
 document.body.appendChild(i);

我在Chrome中收到了一个奇怪的回复。表单提交的响应显示在阻止的弹出窗口中(而不是我所期望的完全没有)。在IE中似乎没有发生太多事情。

最佳答案

我建议最初使用write()直接写入文档。

演示:http://jsfiddle.net/QjPuZ/1/

码:

var iframeDoc = i.contentDocument || i.contentWindow.document;

iframeDoc.open();
iframeDoc.write("<html><body></body></html>");
iframeDoc.close();

iframeBody = iframeDoc.body;
var frm = iframeDoc.createElement('form');
var s = iframeDoc.createElement('script');
iframeBody.appendChild(frm);
iframeBody.appendChild(s);

09-30 19:00
查看更多