方法:
1.formSerilize() 用於序列化表單中的數據,並將其自動整理成適合AJAX異步請求的URL地址格式。
2.clearForm() 清除表單中所有輸入值的內容。
3.restForm 重置表單中所有的字段內容。即將所有表單中的字段恢復到頁面加載時的默認值。
疑問:ajaxForm()與ajaxSubmit()的區別:
答案:$("#form1").ajaxForm(); 相當於以下兩行:
1
2
3
4
|
$(
"#form1"
.submit)(
function
(){
$(
"#form1"
).ajaxSubmit();
return
false
;
})
|
也就是說ajaxFrom()會自動阻止表單提交。而ajaxSubmit()不會自動阻止表單提交,想阻止表單提交,要自己return false;
技巧1:如果希望表單提交完成后不跳轉,那么一行簡單的代碼就能夠實現,幾乎與不使用表單提交是一樣的:
1
2
3
|
$(
"#MailForm"
).ajaxSubmit(
function
(message) {
alert(
"表單提交已成功!"
);
});
|
注意:ajaxForm()與ajaxForm()都可以沒有參數或者接受1個參數。該參數既可以是一個回調函數,也可以是一個options對象。該對象功能非常強大,說明如下:
1
2
3
4
5
6
7
8
9
10
11
|
var
options={
url:url,
//form提交數據的地址
type:type,
//form提交的方式(method:post/get)
target:target,
//服務器返回的響應數據顯示在元素(Id)號確定
beforeSubmit:
function
(),
//提交前執行的回調函數
success:
function
(),
//提交成功后執行的回調函數
dataType:
null
,
//服務器返回數據類型
clearForm:
true
,
//提交成功后是否清空表單中的字段值
restForm:
true
,
//提交成功后是否重置表單中的字段值,即恢復到頁面加載時的狀態
timeout:6000
//設置請求時間,超過該時間后,自動退出請求,單位(毫秒)。
}
|
例子:
頁面js代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
<script src=
"jQuery.1.8.3.js"
type=
"text/javascript"
></script>
<script src=
"jQuery.Form.js"
type=
"text/javascript"
></script>
<script type=
"text/javascript"
>
$(
function
() {
$(
":submit"
).click(
function
() {
var
options = {
url:
"indexAjax.aspx"
,
target:
"#div2"
,
success:
function
() {
alert(
"ajax請求成功"
);
}
};
$(
"#form1"
).ajaxForm(options);
})
})
</script>
|
頁面HTML代碼:
1
2
3
4
5
6
7
8
9
10
|
<
div
id
=
"div1"
>
<
form
id
=
"form1"
method
=
"get"
action
=
"#"
>
<
p
>我的名字:<
input
type
=
"text"
name
=
"name"
value
=
"請輸入內容"
/></
p
>
<
p
>我的偶像是:<
input
type
=
"radio"
name
=
"Idol"
value
=
"劉德華"
/>劉德華 <
input
type
=
"radio"
name
=
"Idol"
value
=
"張學友"
/>張學友</
p
>
<
p
>我喜歡的音樂類型:<
input
type
=
"checkbox"
name
=
"musictype"
value
=
"1.搖滾"
>搖滾 <
input
type
=
"checkbox"
name
=
"musictype"
value
=
"2.輕松"
>輕柔 <
input
type
=
"checkbox"
name
=
"musictype"
value
=
"3.爵士"
>爵士</
p
>
<
p
><
input
type
=
"submit"
value
=
"確認"
/></
p
>
</
form
>
</
div
>
<
div
id
=
"div2"
>
</
div
>
|
后台:indexAjax.aspx.cs代碼
1
2
3
4
5
6
7
8
9
|
protected
void
Page_Load(
object
sender, EventArgs e)
{
string
strName = Request[
"name"
];
string
strIdol = Request[
"Idol"
];
string
strMusicType = Request[
"musictype"
];
Response.Clear();
Response.Write(
"我的名字是:"
+ strName +
"; 我的偶像是:"
+ strIdol +
"; 我喜歡的音樂類型:"
+ strMusicType);
Response.End();
}
|
自己做的demo:
<form action="" method="POST" name='formUpdate'enctype="multipart/form-data" role="form" id="addActivity" >
<input type="submit" class="btn btn-info create-activity" value="保存">
</form>
$(".create-activity").on("click",function(){
$("#addActivity").submit(function(){
$(this).ajaxSubmit({
url:"/activity/operate",
success:function(data){
alert(data['msg'])
window.location.href="...."
return false;
},
resetForm:true,
dataType:'json'
})
return false;
})
}