專案需實現資料庫瀏覽樹:點擊資料庫節點 → 異步載入資料表 → 點擊資料表節點 → 異步載入欄位。後端提供 REST API,前端使用 jstree 渲染與交互。
# 獲取根節點(資料庫列表)
GET /api/databases
Response: [{"id": "db1", "text": "用戶庫", "children": true}, {"id": "db2", "text": "訂單庫", "children": true}]
# 獲取子節點(根據父節點 ID 和類型)
GET /api/nodes?parentId=db1&parentType=database
Response: [{"id": "tbl_users", "text": "users", "type": "table", "children": true}, ...]
GET /api/nodes?parentId=tbl_users&parentType=table
Response: [{"id": "col_id", "text": "id (PK)", "type": "column", "icon": "jstree-file"}, ...]
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>jstree 動態載入示例</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jstree@3.3.12/dist/themes/default/style.min.css">
<script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jstree@3.3.12/dist/jstree.min.js"></script>
</head>
<body>
<div id="db-tree" style="width: 300px; height: 500px; border: 1px solid #ccc;"></div>
<script>
$(function() {
$('#db-tree').jstree({
'core': {
'data': {
'url': '/api/databases', // 根節點
'dataType': 'json',
'cache': false,
'data': function(node) {
// 子節點動態載入參數
return {
'parentId': node.id === '#' ? '' : node.id,
'parentType': node.id === '#' ? '' : node.type
};
}
},
'themes': {
'dots': true,
'icons': true
}
},
'types': {
'database': { 'icon': 'jstree-folder' },
'table': { 'icon': 'jstree-folder' },
'column': { 'icon': 'jstree-file', 'valid_children': [] }
},
'plugins': ['types', 'wholerow', 'contextmenu']
}).on('select_node.jstree', function(e, data) {
var node = data.node;
console.log('選中節點:', node.id, node.text, node.type);
// 業務邏輯:顯示欄位詳情、生成 SQL 等
});
});
</script>
</body>
</html>
| 配置項 | 作用 | 關鍵點 |
|---|---|---|
core.data.url | 根節點/子節點統一端點 | jstree 會自動在請求參數中傳遞 id(父節點 ID,根為 #) |
core.data.data | 自定義請求參數 | 函數接收 node 參數,返回物件合併到 AJAX data |
types | 節點類型樣式/行為 | 定義 database/table/column 圖標、可否有子節點 |
plugins: ['wholerow'] | 整行選中高亮 | 提升點擊體驗,避免僅點擊文字才選中 |
valid_children: [] | 葉子節點禁止展開 | 欄位節點 column 設置為空陣列,防止顯示展開箭頭 |
'contextmenu': {
'items': function(node) {
var items = {
'create': { 'label': '新建資料表', 'action': function() { /* AJAX POST */ } },
'rename': { 'label': '重命名' },
'remove': { 'label': '刪除' }
};
if (node.type === 'column') delete items.create; // 欄位不可建子節點
return items;
}
}
$('#search-input').on('keyup', function() {
$('#db-tree').jstree(true).search($(this).val());
});
?parentId=xxx&page=1&size=100jquery.jstree.lazy.js 或自定義滾動加載db1.tbl_users.col_id 格式)core.data 必須返回 Promise 或使用回調,**不能**同步返回 AJAX 結果state plugin + localStorage/後端儲存完整 Demo 可參考 官方文檔 core.data 章節,結合上述代碼即可快速落地資料庫→資料表→欄位三級動態樹。