本文實例講述了jQuery插件之jQuery.Form.js用法。分享給大家參考,具體如下:
一、jQuery.Form.js 外掛程式的作用是實作Ajax提交表單。
方法:
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,
type:type,
target:target,
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 ();
}
|
登入後複製
範例程式碼點擊此處本站下載。
更多jQuery外掛用法也可參考本站相關專題:《jQuery常用插件及用法總結》。
希望本文所述對大家jQuery程式設計有所幫助。