iframe里面提交表单页面跳转问题

问题描述:

在使用iframe方式异步上传文件时,ie7对name属性的处理有些不同,如果采用先创建iframe,再使用setAttribute方法添加name属性的方式,form提交数据返回时会找不到iframe,从而会新打开一个页面。

ie7下会失败的例子:

复制代码
var iframe = document.createElement('iframe');
iframe.setAttribute('id', 'IframeNode');
iframe.setAttribute('name', 'IframeNode');
iframe.style.display = 'none';
document.body.appendChild(iframe);


iframe.onload = function(){
    document.getElementById('Result').innerHTML = 
        iframe.contentWindow.document.body.innerHTML;
}

var form = document.getElementById('Form');
form.target = 'IframeNode',
form.action = '/php/create_iframe.php';

form.submit();
复制代码

有两种方法可以解决这个问题。

首先,不能使用setAttribute方法来设置name属性;

然后,

1. 用这种方式创建iframe

var iframe = document.createElement('<iframe name="IframeNode"></iframe>');

这种方式ie9以下可用。

2. 创建完iframe之后通过这种方式添加name属性

iframe.contentWindow.name = 'IframeNode';

这种方法所有浏览器都可用。

转自http://www.cnblogs.com/zhaoran/archive/2013/05/23/3094951.html

原文地址:https://www.cnblogs.com/lr-blog/p/5341693.html