1. 程式人生 > >非ajax方式提交表單不重新整理頁面

非ajax方式提交表單不重新整理頁面

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();