下拉選單的選項如果來自資料庫,通常沒辦法寫死在 HTML 裡。本文示範如何用 jQuery 的 ajax 在頁面載入時把選項抓回來並填進 select。
<head>
<title>jquery實現動態加載select下拉選項</title>
<script type="text/javascript">
function init(){
makemoduleSelect();
}
// 載入模板下拉框選項
function makemoduleSelect(){
$.ajax({
url : 'indexStatisticsAction_getSelect.jsp',
data: { page: 'clientindexStatistics.jsp', method: 'get_modtitlecode' },
success : function(result){
$("#makemodule").append(result);
}
});
}
</script>
</head>
<body onload="init()">
下拉框
<select name="makemodule" id="makemodule" style="width:130px"
onchange="makemoduleSelected()">
<option> ------- </option>
</select>
</body>
流程是這樣的:HTML 載入時 body 的 onload 觸發 init(),呼叫 makemoduleSelect() 發出 ajax 請求。三個屬性各有分工:url 類似 ajax 的跳轉位址;data 會作為請求參數由 request 取得;success 是請求成功後要執行的程式碼,這裡的 $("#makemodule") 指的就是那個 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");
if (method.equals("get_modtitlecode")) {
String sql = "select modtitlename, modtitlecode from makemodule "
+ "where userid = ? and modulename_en = ? group by modtitlename ";
// 依來源頁面決定 modulename_en 的條件
StringBuffer rsOption = new StringBuffer();
ResultSet rs = db.executeQuery(sql);
while (rs != null && rs.next()) {
rsOption.append("<option value='" + rs.getString("modtitlecode")
+ "'>" + rs.getString("modtitlename") + "</option>");
}
PrintWriter pout = response.getWriter();
pout.write(rsOption.toString());
pout.flush();
pout.close();
}
%>
做法是撈出兩個欄位,一個當 select 的顯示值、一個當真值,套上 option 標籤後整串回傳。前端收到字串直接 append 進 select 即可。
原始碼用字串 replace 拼 SQL(把 ?userId? 之類的佔位符替換掉),這有 SQL Injection 風險。請改用 PreparedStatement 搭配真正的 ? 佔位符:
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, userId);
ps.setString(2, moduleName);
ResultSet rs = ps.executeQuery();
其次,用 JSP 直接寫業務邏輯加資料庫存取的 1996 年風格寫法,很難測試也不好維護。建議把查詢抽到 DAO/Service 層,前端改成請求一個回傳 JSON 的 API。
最後,前端這邊有兩個實務細節:onload 屬性已不建議使用,改成 $(function(){ ... }) 或 DOMContentLoaded;ajax 缺乏錯誤處理,一旦請求失敗使用者只會看到空的選單,應該補上 error 或 .fail() 給出提示。若改成回傳 JSON,前端組 option 也會比直接 append HTML 字串安全:
fetch('/api/modtitlecode?method=get_modtitlecode')
.then(function(r){ return r.json(); })
.then(function(list){
var $sel = $('#makemodule');
list.forEach(function(item){
$sel.append($('<option>').val(item.code).text(item.name));
});
});
用 jQuery 建元素而非拼字串,可以避免資料中含有引號或角括號時把 HTML 結構打壞——這是動態組 option 最常踩的坑。