DIV CSS 佈局教程網

ajaxSubmit 非同步送出表單的前後端搭配
編輯:JQuery特效代碼     

ajaxSubmit() 出自 jQuery Form 外掛,比手動 serialize 再呼叫 $.ajax() 更省事,尤其是表單裡有檔案上傳時。

前端

$("#nickForm").ajaxSubmit({
    type: "post",
    url: "https://localhost:8080/test/myspace.do?method=updateNick&param=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();
}

幾個容易忽略的細節

dataType 決定 result 的型別:宣告 "json",jQuery 會自動把回應字串解析成物件,所以後面可以直接 result.nickMsg。若忘了設定,拿到的會是字串,取值就會是 undefined。

回應的 Content-Type:後端最好明確輸出 application/json; charset=UTF-8,並在取得 Writer 之前呼叫 response.setCharacterEncoding("UTF-8"),否則中文提示容易變成亂碼。

記得引入 jquery.form.js:ajaxSubmit() 不是 jQuery 核心方法,少了外掛會直接報函式不存在。

另外,如果表單需要欄位驗證,可以在 options 中加上 beforeSubmit 回呼,回傳 false 就能中止送出;成功後若想清空表單,用 resetForm: true 或 clearForm: true 即可。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved