form表單提交的幾種方法
在form標簽中添加Action(提交的地址)和method(post),且有一個submit按鈕
(<input type='submit'>)就可以進行數據的提交,每一個input標簽都需要有一個name屬性,才能進行提交
當點擊登陸時,向數據庫發生的數據是:username=username&password=password.
這種默認的提交方式,一般會進行頁面的跳轉(不成功時跳轉到當前頁面)。而有時候我們是對彈出框進行數據提交的,希望提交成功則關閉彈出框並刷選父頁面,失敗則提示失敗原因,且彈出框不關閉。此時可以采用Ajax進行數據提交.
具體參考第四種方案
無刷新頁面提交表單
表單可實現無刷新頁面提交,無需頁面跳轉,如下,通過一個隱藏的iframe實現,form表單的target設置為iframe的name名稱,
form提交目標位當前頁面iframe則不會刷新頁面
1
2
3
4
|
<form
action
=
"/url.do"
method=
"post"
target=
"targetIfr"
>
<input type=
"text"
name
=
"name"
/>
</form>
<iframe
name
=
"targetIfr"
></iframe>
|
通過type=submit提交
一般表單提交通過type=submit實現,input type=”submit”,瀏覽器顯示為button按鈕,通過點擊這個按鈕提交表單數據跳轉到/url.do
1
2
3
4
|
<form
action
=
"/url.do"
method=
"post"
>
<input type=
"text"
name
=
"name"
/>
<input type=
"submit"
value=
"提交"
>
</form>
|
js提交form表單
js事件觸發表單提交,通過button、鏈接等觸發事件,js調用submit()方法提交表單數據,jquery通過submit()方法
1
2
3
4
5
6
7
8
9
10
|
<form id=
"form"
action
=
"/url.do"
method=
"post"
>
<input type=
"text"
name
=
"name"
/>
</form>
<script>
document.getElementById(
"form"
).submit();
jquery: $(
"#form"
).submit();
</script>
|
ajax異步提交表單數據
采用ajax異步方式,通過js獲取form中所有input、select等組件的值,將這些值組成Json格式,通過異步的方式與服務器端進行交互,一般將表單數據傳送給服務器端,服務器端處理數據並返回結果信息等
1
2
3
4
5
6
7
8
9
10
11
12
|
<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){
}
});
|
此時可以在callback函數中對請求結果進行判斷,然后執行不同的動作(頁面跳轉或刷選數據、提醒錯誤都可以)
頁面無跳轉
如果通過form表單提交請求服務端去下載文件,這時當前頁面不會發生跳轉,服務端返回void,通過response 去寫文件數據,頁面會顯示下載文件。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
<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
();
}
}
}
|
form表單上傳文件
使用form表單進行上傳文件需要為form添加enctype=”multipart/form-data” 屬性,除此之外還需要將表單的提交方法改成post,如下 method=”post”, input type的類型需要設置為file
1
2
3
4
|
<form
action
=
"/url.do"
enctype=
"multipart/form-data"
method=
"post"
>
<input type=
"file"
name
=
"name"
/>
<input type=
"submit"
value=
"提交"
>
</form>
|
附件只能通過submit方法進行提交,