不需要任何特殊標記,就是最一般的 form:
<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>
此時若沒有引入 Form 外掛,按下送出後瀏覽器會進入等待狀態,畫面被同步提交卡住,直到伺服器回應。
<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">
// 等 DOM 就緒
$(document).ready(function() {
// 為 myForm 綁定 ajaxForm 非同步提交,並提供一個簡單的回呼
$('#myForm').ajaxForm(function() {
alert("感謝您的填寫!");
});
});
</script>
</head>
掛上外掛之後,表單不再同步送出,而是交給 JS 以 Ajax 處理,因此提交後頁面不會刷新。
$(document).ready(function () {
// options 是 ajaxForm 的設定物件
var options = {
//target: '#output1', // 用來承接伺服器回應的元素
//beforeSubmit: showRequest, // 提交前的回呼
success: callBackFunc // 提交後的回呼
// 其他可用選項:
//url: url // 覆寫表單的 action
//type: type // 'get' 或 'post',覆寫 method
//dataType: null // 'xml'、'script' 或 'json'
//clearForm: true // 成功後清空所有欄位
//resetForm: true // 成功後重設表單
// $.ajax 的選項也都能用,例如:
//timeout: 3000
};
// 以 ajaxForm 綁定表單
$('#myForm').ajaxForm(options);
});
// responseText 是伺服器的回應內容,statusText 是提交狀態,成功時為 success
function callBackFunc(responseText, statusText) {
if (statusText == 'success') {
alert(responseText);
} else {
alert("伺服器發生錯誤!");
}
}
function resultFunction(responseText, statusText) {
if (statusText == 'success') {
if (responseText.code == 1) {
alert(responseText.message);
} else {
alert('發生錯誤!');
}
} else {
alert('伺服器錯誤!');
}
}
對應的 MVC 服務端寫法:
[HttpPost]
public ActionResult AjaxForm(FormCollection form)
{
string message = "Name:" + form["username"] + " PWD: " + form["password"];
//return Content(message);
return Json(new { code = 1, message = message });
}
在 options 中加上 beforeSubmit,回傳 false 即可中止送出:
var options = {
//target: '#output1',
beforeSubmit: checkData, // 提交前的回呼
success: callBackFunc // 提交後的回呼
// 其餘選項同上,此處省略
};
// 提交前的回呼
function checkData(formData, jqForm, options) {
// formData 是陣列,可用 $.param 轉成字串檢視
// var queryString = $.param(formData);
// jqForm 是包裝表單元素的 jQuery 物件,取原生元素用 jqForm[0]
var formElement = jqForm[0];
// 回傳 false 會阻止提交,回傳其他值則繼續
if ($(formElement).find("#username").val() == "") {
alert("請輸入使用者名稱!");
return false;
} else {
return true;
}
}
如此一來,帳號為空時會提示並取消送出,不必等伺服器回應才發現問題。