這個功能實用、程式碼也相當簡潔,直接分享如下:
$.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("失敗!");
}
}
});
重點是用 $("#form1").serialize() 把表單資料序列化後直接當作 data 送出,再依回傳的 JSON 結果決定要隱藏表單區塊、顯示提示訊息或跳出失敗提醒。希望這段程式碼能幫助大家熟練掌握非同步表單提交。