Form表單的6種提交方式
阿新 • • 發佈:2019-02-11
1.無重新整理頁面提交表單
表單可實現無重新整理頁面提交,無需頁面跳轉,如下,通過一個隱藏的iframe實現,form表單的target設定為iframe的name名稱,
form提交目標位當前頁面iframe則不會重新整理頁面
<form action="/url.do" method="post" target="targetIfr">
<input type="text" name="name"/>
</form>
<iframe name="targetIfr" style="display:none"></iframe>
2.通過type=submit提交
一般表單提交通過type=submit實現,input type="submit",瀏覽器顯示為button按鈕,通過點選這個按鈕提交表單資料跳轉到/url.do
<form action="/url.do" method="post">
<input type="text" name="name"/>
<input type="submit" value="提交">
</form>
3.js提交form表單
<form id="form" action="/url.do" method="post">
<input type="text" name="name"/>
</form>
js: document.getElementById("form").submit();
jquery: $("#form").submit();
4.ajax非同步提交表單資料
採用ajax非同步方式,通過js獲取form中所有input、select等元件的值,將這些值組成Json格式,通過非同步的方式與伺服器端進行互動,一般將表單資料傳送給伺服器端,伺服器端處理資料並返回結果資訊等
<form id="form" method="post">
<input type="text" name="name" id="name"/>
</form>
var params = {"name", $("#name").val()}
$.ajax({
type: "POST",
url: "/url.do",
data: params,
dataType : "json",
success: function(respMsg){
}
});
5.頁面無跳轉如果通過form表單提交請求服務端去下載檔案,這時當前頁面不會發生跳轉,服務端返回void,通過response 去寫檔案資料,
頁面會顯示下載檔案。
<form action="/url.do" method="post">
<input type="text" name="name"/>
<input type="submit" value="提交">
</form>
@RequestMapping(value = "/url")
public void exportFile(HttpServletRequest req, HttpServletResponse response, String rptId)
throws Exception {
OutputStream out = null;
try {
String rptName = "file";
String fileName = new String((rptName + excelAble.getFileSuffix()).getBytes("GBK"),
"8859_1");
response.reset();
response.setContentType("application/octec-stream");
response.setHeader("Content-disposition", "attachment; filename=" + fileName);
out = response.getOutputStream();
excelAble.exportFile(out);
} catch (Exception e) {
logger.error(e);
} finally {
if (out != null) {
out.close();
}
}
}
6.form表單上傳檔案
使用form表單進行上傳檔案需要為form新增enctype="multipart/form-data" 屬性,除此之外還需要將表單的提交方法改成post,
如下 method="post", input type的型別需要設定為file
<form action="/url.do" enctype="multipart/form-data" method="post">
<input type="file" name="name"/>
<input type="submit" value="提交">
</form>