表單送出前先問後端「這個代碼有人用過了嗎」,是即時驗證最典型的應用。以下直接看程式碼。
關鍵是明確設定 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 檢查重複值的實作程式碼,希望對大家有所幫助。