傳統表單提交會導致頁面重載,影響用戶體驗。使用 jQuery 的 $.ajax() 配合 serialize() 方法,能輕鬆實現無刷新表單提交,並靈活處理服務端響應。
$.ajax({
url: "mobileSurveyAction_addSurvey.action", // 提交地址
data: $("#form1").serialize(), // 表單數據序列化
type: "POST",
dataType: "json",
success: function(result) {
if (result.success === '100') {
$("#mySection").hide();
$(".footer").hide();
$("#alertMsg").show();
} else {
alert("提交失敗!");
}
},
error: function(xhr, status, error) {
console.error("請求異常:", error);
alert("網絡錯誤,請稍後重試");
}
});
name 屬性的輸入控件值,拼接為標準查詢字符串error 回調,捕獲網絡異常beforeSend 中禁用提交按鈕,complete 中恢復$("#form1").on("submit", function(e) {
e.preventDefault();
const $btn = $(this).find(":submit").prop("disabled", true);
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
dataType: "json"
}).done(function(res) {
// 處理成功邏輯
}).fail(function() {
alert("提交異常");
}).always(function() {
$btn.prop("disabled", false);
});
});
這種模式廣泛應用於登入、註冊、搜索、評論等場景,是現代 Web 開發的基礎技能。