萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 動態載入 Select 下拉選單完整實作教學

前言

在 Web 開發中,根據使用者操作或頁面初始化動態載入下拉選單選項是常見需求。本文將示範如何搭配 jQuery AJAX 與後端 JSP,實現 Select 元件的動態資料綁定。

核心架構

整個流程分為三個層次:

  • 前端頁面:包含 Select 元素與初始化邏輯
  • jQuery AJAX:非同步請求後端資料
  • 後端 JSP:查詢資料庫並輸出 Option 字串

前端實作

<head>
  <title>jQuery 動態載入 Select 下拉選項</title>
  <script type="text/javascript" src="jquery.min.js"></script>
  <script type="text/javascript">
    function init() {
      loadModuleSelect();
    }

    // 載入模組下拉選單
    function loadModuleSelect() {
      $.ajax({
        url: 'indexStatisticsAction_getSelect.jsp',
        data: {
          page: 'clientindexStatistics.jsp',
          method: 'get_modtitlecode'
        },
        success: function(result) {
          $("#makemodule").append(result);
        },
        error: function(xhr, status, error) {
          console.error("載入失敗:", error);
        }
      });
    }
  </script>
</head>
<body onload="init()">
  下拉選單:
  <select name="makemodule" id="makemodule" style="width:130px" onchange="moduleSelected()">
    <option>-------</option>
  </select>
</body>

關鍵點解析

  1. body onload="init()":頁面載入完成自動觸發初始化
  2. $.ajax 設定 url 指向後端 JSP,data 傳遞查詢參數
  3. success 回呼中使用 $("#makemodule").append(result) 將後端回傳的 <option> 字串直接插入 Select

後端 JSP 實作

<%@ page import="java.util.*" %>
<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.io.PrintWriter" %>
<%
  String userId = (String) session.getAttribute("userid");
  String method = request.getParameter("method");
  String fromPage = request.getParameter("page");

  String sql = "SELECT modtitlename, modtitlecode FROM makemodule " +
               "WHERE userid = ? AND modulename_en = ? GROUP BY modtitlename";

  // 根據來源頁面決定模組英文名稱
  String moduleEn = "";
  if ("acindexStatistics.jsp".equals(fromPage)) moduleEn = "acsta";
  else if ("apindexStatistics.jsp".equals(fromPage)) moduleEn = "apsta";
  else if ("clientindexStatistics.jsp".equals(fromPage)) moduleEn = "terminalsta";

  // 實際專案請使用 PreparedStatement 防止 SQL 注入
  // 此處為示範簡化處理
  sql = sql.replaceFirst("\\?", userId).replaceFirst("\\?", moduleEn);

  System.out.println("--- 執行 SQL: " + sql + " ---");

  StringBuffer options = new StringBuffer();
  Db db = new Db();
  try {
    db.prepareQuery();
    ResultSet rs = db.executeQuery(sql);
    while (rs != null && rs.next()) {
      String code = rs.getString("modtitlecode");
      String name = rs.getString("modtitlename");
      // 處理編碼轉換(視資料庫編碼而定)
      options.append("<option value='").append(code).append("'>")
             .append(name).append("</option>");
    }
    rs.close();
  } catch (Exception e) {
    e.printStackTrace();
  } finally {
    db.endQuery();
  }

  response.setContentType("text/html;charset=UTF-8");
  PrintWriter out = response.getWriter();
  out.write(options.toString());
  out.flush();
  out.close();
%>

安全性補充

實際專案中強烈建議:

  • 使用 PreparedStatement 參數化查詢,避免 SQL 注入
  • 後端改為 Servlet 或 Controller 回傳 JSON 格式,前端再組裝 Option,分離關注點
  • 加入快取機制減少資料庫查詢

完整流程圖解

流程圖

總結

此範例展示了傳統 JSP + jQuery 實現動態下拉選單的基本模式。現代開發建議採用 RESTful API 回傳 JSON,搭配 Vue/React 等前端框架進行資料綁定,但理解此基礎模式有助於維護舊專案或快速原型開發。

copyright © 萬盛學電腦網 all rights reserved