IE问题:使用javascript将表单提交到iframe

Erw*_*win 35 javascript forms iframe

我试图使用javascript创建一个iframe元素,如下所示:

var iframe = document.createElement('iframe');
iframe.setAttribute('name', 'frame_x');
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试使用新创建的iframe作为目标提交表单时,IE会打开一个新窗口,而不是使用iframe.

form.setAttribute('target', 'frame_x');
form.submit();
Run Code Online (Sandbox Code Playgroud)

这在Firefox中完美运行.此外,iframe已创建,但未使用.

scu*_*ffe 74

您已经在Internet Explorer中遇到了一个错误.

您不能使用标准DOM方法在IE中设置ANY元素的name属性.setAttribute('name', value);

在IE(在IE8标准模式下运行的版本8之前),此方法无法设置name属性.

您需要使用以下之一:

//A (any browser)
var iframe = document.createElement('iframe');
iframe.name = 'frame_x';

//B (only in IE)
var iframe = document.createElement('<iframe name="frame_x"/>');

//C (use a JS library that fixes the bug (e.g. jQuery))
var iframe = $('<iframe name="frame_x"></iframe>');

//D (using jQuery to set the attribute on an existing element)
$('iframe:first').attr('name','frame_x');
Run Code Online (Sandbox Code Playgroud)

  • 谢谢scunliffe.这是一个非常有用的信息. (3认同)

AJ.*_*AJ. 7

欢迎来到SO.

我在您的代码中看到的一个问题是,您实际上从未显示过iframe.为了使其显示在页面上,您必须将其插入到文档中.在我的示例中,我创建了一个<span>标记,用作插入iframe的插槽.

看看这是否符合您的要求.

<!-- http://stackoverflow.com/questions/2181385/ie-issue-submitting-form-to-an-iframe-using-javascript -->

<html>
<head>
<script type="text/javascript">
function submitFormToIFrame(){
    var form=document.getElementById('myform');
    form.setAttribute('target', 'frame_x');
    form.submit();
}
</script>
</head>

<body>
<h1>Hello Erwin!</h1>

<form id="myform" name="myform" action="result.html">
    <input type="button" value="Submit the Form" onClick="submitFormToIFrame();">
</form>


<span id="iframeSlot">

<script type="text/javascript">
    var iframe = document.createElement('iframe');
    iframe.setAttribute('name', 'frame_x');
    document.getElementById('iframeSlot').appendChild(iframe);
</script>
</span>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

更新:

我发现这个解决方案只适用于Firefox.所以我做了一些实验.似乎如果你在html中定义iframe(而不是通过JS/DOM生成它),那么它可以工作.这是适用于IE和Firefox的版本:

<html>
<head>
<script type="text/javascript">
function submitFormToIFrame(){
    //IE
    if( document.myform ){
        document.myform.setAttribute('target','frame_x');
        document.myform.submit();
    //FF
    } else {
        var form=document.getElementById('myform');
        form.setAttribute('target', 'frame_x');
        form.submit();
    }
}
</script>
</head>

<body>
<h1>Hello Erwin!</h1>

<form id="myform" name="myform" action="result.html" target="">
    <input type="button" value="Submit the Form" onClick="submitFormToIFrame();">
</form>

<span id="iframeSlot">
<iframe name="frame_x">
</iframe>
</span>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

  • 这里的`if`语句似乎相当冗余,适用于Firefox的代码也适用于IE,因此IE特定的代码没有意义. (2认同)