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对象种写入表单来解决
window.document.write(" <iframe id=\"hidden_frame\" name=\"hidden_frame\" src=\"about:blank\" style=\"display:none;\"></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();