選擇「一級分類」→ 非同步載入對應「二級分類」→ 使用者挑選。經典 Master-Detail 下拉聯動。
parent_id 自關聯)<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<script src="js/jquery.js"></script>
<script src="js/json.js"></script> <!-- 兼容 IE8- -->
<script>
const basePath = '<%= request.getContextPath() %>/';
function loadSubCategories(parentId) {
$.ajax({
url: basePath + 'cateJson.whbs',
method: 'POST',
data: { parentId },
dataType: 'json',
cache: false,
success: renderSubOptions,
error: () => alert('載入失敗,請稍後再試')
});
}
function renderSubOptions(data) {
const $sub = $('#twoId').empty(); // 清空現有 options
if (!data || !data.length) {
$sub.append('<option value="">無子分類</option>');
return;
}
data.forEach(item => {
$sub.append(`<option value="${item.recordId}">${item.title}</option>`);
});
}
// 頁面載入若已有預設一級值,可主動觸發
$(() => {
const initial = $('#oneId').val();
if (initial) loadSubCategories(initial);
});
</script>
<body>
<div style="text-align:center; margin-top:2rem;">
請選擇部門類型:
<s:select name="oneId" id="oneId" list="rfones" listKey="recordId" listValue="title"
onchange="loadSubCategories(this.value)" theme="simple" />
請選擇文件類型:
<s:select name="twoId" id="twoId" list="rftwos" listKey="recordId" listValue="title"
theme="simple" />
</div>
</body>
public class CategoryAction extends ActionSupport {
private String parentId;
private List rfjsons; // 回傳給前端的列表
// getter/setter 省略
@Autowired
private ArchiveService archiveService;
public String getJsonCategory() throws IOException {
// 1. 依 parentId 查詢子分類
rfjsons = archiveService.getCategoryByParentID(parentId);
// 2. 序列化為 JSON 字串
JSONArray jsonArray = JSONArray.fromObject(rfjsons); // json-lib
// 3. 直接寫入回應
HttpServletResponse response = ServletActionContext.getResponse();
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json");
response.getWriter().write(jsonArray.toString());
return NONE; // 不轉向任何結果視圖
}
}
CREATE TABLE category (
record_id VARCHAR(32) PRIMARY KEY,
title VARCHAR(100) NOT NULL,
parent_id VARCHAR(32), -- 自關聯,根節點 parent_id = '0' 或 NULL
sort_order INT DEFAULT 0
);
fetch + async/await,移除 json2.js;選單元件化(Vue/React Select)。@RestController 直接回傳 List<Category>,Jackson 自動序列化 JSON。localStorage 快取;二級分類後端加 Redis 快取 10 分鐘。aria-controls、aria-expanded、鍵盤操作支援。pageEncoding="UTF-8"、Response setCharacterEncoding("UTF-8")、資料庫連線 characterEncoding=utf8。NONE,且無其他攔截器輸出內容。ezmorph、commons-lang、commons-beanutils、commons-collections、commons-logging 版本相容。POST + cache: false 避免。此經典聯動模式奠基於「前端觸發 → 後端查詢 → JSON 回傳 → 前端渲染」四步驟,掌握核心流程即可靈活套用至任何技術棧。