DIV CSS 佈局教程網

用AJAX查詢資料庫並把結果填回頁面
編輯:AJAX基礎知識     

需求

在JSP頁面的文字框中填入客戶編號,當游標離開該欄位時,自動到資料庫查詢,並在頁面對應位置顯示這筆編號的其他資訊。

Servlet端

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——彈窗會打斷操作。
  • 後端輸出前務必轉義HTML,避免資料中的標籤被執行。
  • 若客戶編號會出現在網址上,同樣記得編碼;敏感欄位則不該用GET傳遞。

整體流程就是一個典型的「欄位離焦 → 非同步查詢 → 局部更新」模式,把它做熟之後,即時驗證、自動帶出關聯資料等需求都能套用同一套骨架。

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