在JSP頁面的文字框中填入客戶編號,當游標離開該欄位時,自動到資料庫查詢,並在頁面對應位置顯示這筆編號的其他資訊。
request.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
// 呼叫service層依編號查詢
String client_id = request.getParameter("client_id");
ClientServices clientServices = new ClientServices();
try {
Thread.sleep(2000); // 模擬查詢耗時,方便觀察loading狀態
} catch (InterruptedException e) {
e.printStackTrace();
}
Client client = clientServices.findClientById(client_id);
if (client != null){
out.print(URLEncoder.encode(client.getClient_name(), "utf-8"));
} else {
out.print("false");
}
out.flush();
out.close();
幾個要點:開頭設定請求編碼避免中文亂碼;查無結果時回傳字串 false 作為哨兵值,讓前端得以區分「查不到」與「查到內容為空」;回傳前用 URLEncoder 編碼,與前端的解碼成對出現。
$(document).ready(function(){
$('#client_id').blur(function(){
$.ajax({
type: 'POST',
url: 'servlet/validServlet?client_id=' + $(this).val(),
data: 'client_id=' + $('#client_id').val(),
success: function(msg){
if (msg == 'false'){
alert('沒有此人');
} else {
// decodeURI 解碼,解決中文亂碼
$('#clientInfo').html(decodeURI(msg));
$('#clientInfo').attr('value', decodeURI(msg));
}
}
});
});
});
用 blur 而非 keyup 觸發,可以避免每打一個字就查一次資料庫;若改用 keyup,務必加上延遲(debounce)控制請求頻率。
Thread.sleep 就是為了凸顯這個需求。alert——彈窗會打斷操作。整體流程就是一個典型的「欄位離焦 → 非同步查詢 → 局部更新」模式,把它做熟之後,即時驗證、自動帶出關聯資料等需求都能套用同一套骨架。