前端調用
$("#nickForm").ajaxSubmit({
type: "post",
url: "https://localhost:8080/test/myspace.do?method=updateNick¶m=1",
dataType: "json",
success: function(result) {
alert(result.nickMsg); // 顯示服務端返回消息
}
});
後端封裝
public ActionForward toUpdateNickName(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
PrintWriter pw = response.getWriter();
JSONObject obj = new JSONObject();
obj.put("nickMsg", "昵稱修改成功!");
pw.print(obj);
pw.close();
return null; // AJAX 不需視圖跳轉
}
關鍵點
ajaxSubmit 來自 jquery.form.js 插件,自動序列化表單數據
dataType: "json" 自動解析響應為 JS 對象
- 後端直接輸出 JSON 字符串,無需視圖解析器
- 適用於簡單表單提交場景,複雜驗證建議用
ajaxForm 配合 beforeSubmit