DIV CSS 佈局教程網

用 Ajax 即時檢查欄位是否重複
編輯:AJAX基礎知識     

表單送出前先問後端「這個代碼有人用過了嗎」,是即時驗證最典型的應用。以下直接看程式碼。

一、Controller 層

關鍵是明確設定 Content-Type 與編碼,然後把字串寫進輸出串流:

@ResponseBody
@RequestMapping("entityFindByCode")
public String entityFindByCode(Entity bean, HttpSession httpSession, Model m,
        HttpServletResponse res) throws IOException {
    res.setContentType("text/plain; charset=UTF-8");
    // res.reset();

    String data = null;
    @SuppressWarnings("unchecked")
    List<Entity> list = (List<Entity>) this.service.find(
        "beanByCode", "Entity", new Object[]{bean.getCode()});

    if (list.size() == 0) {
        data = "YES";     // 沒有重複,可用
    } else {
        data = "NO";      // 已存在
    }

    res.getOutputStream().write(data.getBytes());
    return data;
}

這裡刻意用 getOutputStream() 而不是 getWriter(),並在字串上標明 charset=UTF-8,避免中文訊息出現亂碼。注意:同一個 response 只能選擇 getWriter() 或 getOutputStream() 其中一種,兩者混用會丟出 IllegalStateException。

二、前端頁面

$.ajax({
    url: 'entityFindByCode',
    type: 'post',
    dataType: 'text',
    data: { code: $("#code").val() },        // {key, value}
    success: function (data) {
        if (data == "YES") {
            document.getElementById("msg-code").innerHTML =
                "(<fmt:message key='warn.field.required.unique' bundle='${bundle}' />)";
            return true;
        } else {
            $("#div-code").addClass("has-error");
            document.getElementsByName("code")[0].value = "";
            document.getElementById("msg-code").innerHTML =
                "(<fmt:message key='warn.duplicate' bundle='${bundle}' /> !!!)";
            return false;
        }
    }
});

幾個可以再加強的地方:一是把這段邏輯綁在輸入框的 blur 或 change 事件上,而不是等送出;二是加上 debounce(例如 300ms),避免每敲一個字就打一次後端;三是把 return true/false 改為回傳狀態給外層變數或 Promise,因為 Ajax 是非同步的,return 在回呼函式裡並不會中斷表單送出——這是最常見的誤解。若要真正阻擋送出,需要把驗證結果存成全域旗標,在 submit 事件中判斷。

以上就是 Ajax 檢查重複值的實作程式碼,希望對大家有所幫助。

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