jQuery Form Plugin 讓普通表單具備 AJAX 異步提交能力,避免頁面刷新阻塞。使用前需引入 jQuery 與插件腳本:
<script src="path/to/jquery.js"></script>
<script src="path/to/form.js"></script>
DOM 就緒後初始化表單:
$(document).ready(function() {
$('#myForm').ajaxForm(function() {
alert("Thank you for your comment!");
});
});
表單 HTML 無需特殊標記:
<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>
通過配置對象控制提交行為:
var options = {
// target: '#output1', // 服務端響應填充的目標元素
// beforeSubmit: showRequest, // 提交前回調
success: callBackFunc, // 提交後回調
// url: url, // 覆蓋 form 的 action
// type: type, // 'get' 或 'post',覆蓋 method
// dataType: null, // 'xml', 'script', 'json'
// clearForm: true, // 成功後清空表單
// resetForm: true, // 成功後重置表單
// timeout: 3000 // 超時毫秒數
};
$('#myForm').ajaxForm(options);
function callBackFunc(responseText, statusText) {
if (statusText == 'success') {
alert(responseText);
} else {
alert("服務端錯誤!");
}
}
// 若返回 JSON 格式
function resultFunction(responseText, statusText) {
if (statusText == 'success') {
if (responseText.code == 1) {
alert(responseText.message);
} else {
alert('error occurs!');
}
} else {
alert('服務器錯誤!');
}
}
[HttpPost]
public ActionResult AjaxForm(FormCollection form) {
string message = "Name:" + form["username"] + " PWD: " + form["password"];
return Json(new { code = 1, message = message });
}
var options = {
beforeSubmit: checkData,
success: callBackFunc
};
function checkData(formData, jqForm, options) {
var formElement = jqForm[0];
// 可在此進行驗證,返回 false 可阻止提交
return true;
}
formData 為數組格式,jqForm 封裝表單的 jQuery 對象。插件會自動將數據轉為查詢字符串提交。