Ajax最大的特点就是可以不刷新页面而实现数据的通信及更改页面信息。那么用AJAX进行后台通信传递字符串还是可以的,遇到上传文件该怎么办呢?基于安全考虑,JS是不能直接进行文件操作的,只好用原始的from来提交文件上传了。这样一来,用form不就要刷新页面了吗?其实也不是。
这是网上找的一个一般通用的处理方法
给我们的from加一个target属性,并且将这个属性的值设置为隐藏的iframe的ID,这样一来,刷新的页面是我们隐藏的iframe,我们的页面就不会刷新了。这个方法,时广大前辈的知识和经验的结晶,我是不费吹灰之力拿来用了,站在巨人的肩膀上。
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>AjaxUpload</title>
</head>
<body onLoad="javascript:alert('onload')" onUnload="javascript:alert('onunload')">
<form name="AjaxUpload" method="post" action="upload.jsp" target="hidden_frame">
<input type="submit" name="Submit" value="提交">
</form>
<iframe name='hidden_frame' id="hidden_frame" style="display:none"></iframe>
</body>
</html>
但这种当动态生的的表单貌似无效比如
<iframe name='hidden_frame' id="hidden_frame" style="display:none"></iframe>
document.write("<form action=${adminPath}/charts/echarts/xxx method=post target="hidden_frame" name=form1 id=form1 style='display:none'>");
document.write("<input type=hidden name='name' value='xxx'/>")
document.write("<input type=hidden name='username' value='xxx'/>")
document.write("</form>")
document.form1.submit();
解决办法
可以直接往iframe的dom对象种写入表单来解决
body里加iframe<iframe id="rfFrame" name="rfFrame" src="about:blank" style="display:none;"></iframe>
js新建iframe
var iframe = document.createElement('iframe');
iframe.src="about:blank";
iframe.id="rfFrame";
iframe.name="rfFrame";
iframe.style="display:none;";
document.body.appendChild(iframe);
var window1=$("#rfFrame")[0].contentWindow;
window1.document.write("<form action=${adminPath}/charts/echarts/xxx method=post target="hidden_frame" name=form1 id=form1 style='display:none'>");
window1.document.write("<input type=hidden name='name' value='xxx'/>")
window1.document.write("<input type=hidden name='username' value='xxx'/>")
window1.document.write("</form>")
window1.document.form1.submit();
本文介绍了一种使用Ajax进行文件上传而不刷新页面的方法。通过设置form的target属性为隐藏的iframe,实现在后台通信中上传文件,同时保持页面状态不变。此外,提供了动态生成表单并提交到iframe的有效解决方案。

1352

被折叠的 条评论
为什么被折叠?



