在 Web 開發中,根據使用者操作或頁面初始化動態載入下拉選單選項是常見需求。本文將示範如何搭配 jQuery AJAX 與後端 JSP,實現 Select 元件的動態資料綁定。
整個流程分為三個層次:
<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>
body onload="init()":頁面載入完成自動觸發初始化$.ajax 設定 url 指向後端 JSP,data 傳遞查詢參數success 回呼中使用 $("#makemodule").append(result) 將後端回傳的 <option> 字串直接插入 Select<%@ 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 注入
此範例展示了傳統 JSP + jQuery 實現動態下拉選單的基本模式。現代開發建議採用 RESTful API 回傳 JSON,搭配 Vue/React 等前端框架進行資料綁定,但理解此基礎模式有助於維護舊專案或快速原型開發。