1. 在你的頁面裏寫一個表單。一個普通的表單,不需要任何特殊的標記:
<form id="myForm" method="post" action="/Home/AjaxForm">
<div>
Name:<input id="username" name="username" type="text" />
Password:<input id="password" name="password" type="text" />
<br />
<input type="submit" value="submit async" id="lnkSubmit" />
</div>
</form>
在沒有Jquery.Form組件的時候,提交表單,頁面會進入阻塞模式,等待服務器端的響應。
2. 引入jQuery和Form Plugin Javascript腳本文件並且添加幾句簡單的代碼讓頁面在DOM加載完成後初始化表單:
<head>
<script type="text/javascript" src="path/to/jquery.js"></script>
<script type="text/javascript" src="path/to/form.js"></script>
<script type="text/javascript">
// wait for the DOM to be loaded
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
// 爲myform綁定ajaxForm異步提交事件,並提供一個簡單的回調函數。
$('#myForm').ajaxForm(function() {
alert("Thank you for your comment!");
});
});
</script>
</head>
加上jquery.form組件後,提交表單時,頁面不會再同步提交,而是由js做異步提交,因此提交後頁面不會有刷新。
3. 加入能夠與服務器端進行交互的回調函數。
1
|
$(document).ready( function () { |
//options是一個ajaxForm的配置對象。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
var options = { //target: '#output1', // target element(s) to be updated with server response //beforeSubmit: showRequest, // pre-submit callback <font color= "#ff0000" > success: callBackFunc // post-submit callback</font>
// other available options: //url: url // override for form's 'action' attribute //type: type // 'get' or 'post', override for form's 'method' attribute //dataType: null // 'xml', 'script', or 'json' (expected server response type) //clearForm: true // clear all form fields after successful submit //resetForm: true // reset the form after successful submit // $.ajax options can be used here too, for example: //timeout: 3000 }; // bind form using 'ajaxForm' $( '#myForm' ).ajaxForm(options); }); |
1
|
// responseText是服務端的響應值。statusText是頁面 |
1
2
3
4
5
|
// 提交狀態值,success表示成功。 function
callBackFunc(responseText, statusText) { if (statusText ==
'success' ) { alert(responseText); } |
1
|
else { |
1
|
alert(“服務端錯誤!”); |
1
2
|
} } |
1
|
如果返回的是json數據則回調函數可以這麼寫 |
1
2
3
4
5
6
7
8
9
10
11
12
13
|
function
resultFunction(responseText,statusText) { if (statusText ==
'success' ) {
if (responseText.code == 1) {
alert(responseText.message);
}
else {
alert( 'error occurs!' );
} } else {
alert( '服務器錯誤!' ); } } |
服務端的代碼如下
1
2
3
4
5
6
7
|
[HttpPost] public
ActionResult AjaxForm(FormCollection form) { string message =
"Name:" + form[ "username" ] + " PWD: " +form[ "password" ]
; //return Content(message); return Json( new
{ code = 1, message = message }); } |
4. 加入提交前的數據校驗函數
爲options對象添加 beforeSubmit屬性
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
var
options = {
//target: '#output1', // target element(s) to be updated with server response
<font color= "#ff0000" >beforeSubmit: checkData, // pre-submit callback
</font> success: callBackFunc // post-submit callback
// other available options:
//url: url // override for form's 'action' attribute
//type: type // 'get' or 'post', override for form's 'method' attribute
//dataType: null // 'xml', 'script', or 'json' (expected server response type)
//clearForm: true // clear all form fields after successful submit
//resetForm: true // reset the form after successful submit
// $.ajax options can be used here too, for example:
//timeout: 3000
}; |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
// pre-submit callback function checkData(formData, jqForm, options) { // formData is an array; here we use $.param to convert it to a string to display it // but the form plugin does this for you automatically when it submits the data //var queryString = $.param(formData); // jqForm is a jQuery object encapsulating the form element. To access the // DOM element for the form do this: var formElement = jqForm[0];
//alert('About to submit: \n\n' + queryString);
// here we could return false to prevent the form from being submitted;
// returning anything other than false will allow the form submit to continue
//return true;
if ($(formElement).find( "#username" ).val() == "" ) {
alert( "please enter username!" );
return false ;
} else
{
return true ;
} } |
驗證用戶名是否爲空,是則提示輸入,並取消表單提交。
1.使用post提交方式 2.構造表單的數格式 3.結合form表單的submit調用ajax的回調函數。 使用 jQuery 異步提交表單代碼: 複製代碼 代碼如下: <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>無標題頁</title> </head> <script src="js/jquery-1.4.2.js"></script> <script> jQuery(function($) { // 使用 jQuery 異步提交表單 $('#f1').submit(function() { $.ajax({ url: 'ta.aspx', data: $('#f1').serialize(), type: "post", cache : false, success: function(data) {alert(data);} }); return false; }); }); </script> <body> <form id="f1" name="f1"> <input name="a1" /> <input name="a2" /> <input id="File1" type="file" name="File1"/> <input id="Submit1" type="submit" value="submit" /> </form> </body> </html>
如何異步跨域提交表單呢? 1.利用script 的跨域訪問特性,結合form表單的數據格式化,所以只能採用get方式提交,爲了安全,瀏覽器是不支持post跨域提交的。 2.採用JSONP跨域提交表單是比較好的解決方案。 3.也可以動態程序做一代理。用代理中轉跨域請求。 使用 jQuery 異步跨域提交表單代碼: 複製代碼 代碼如下: <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>無標題頁</title> </head> <script src="js/jquery-1.4.2.js"></script> <script> jQuery(function($) { // 使用 jQuery 異步跨域提交表單 $('#f1').submit(function() { $.getJSON("ta.aspx?"+$('#f1').serialize()+"&jsoncallback=?", function(data) { alert(data); }); return false; }); }); </script> <body> <form id="f1" name="f1"> <input name="a1" /> <input name="a2" /> <input id="File1" type="file" name="File1"/> <input id="Submit1" type="submit" value="submit" /> </form> </body> </html>