在JavaScript中读取数据库数据并生成树状图通常涉及以下几个步骤:
假设我们有一个简单的数据库表categories
,结构如下:
| id | name | parent_id | |----|----------|-----------| | 1 | Electronics | NULL | | 2 | Computers | 1 | | 3 | Laptops | 2 | | 4 | Smartphones | 1 |
我们可以使用JavaScript和AJAX从服务器获取这些数据,并生成一个树状图。
const express = require('express');
const app = express();
app.get('/api/categories', (req, res) => {
const categories = [
{ id: 1, name: 'Electronics', parent_id: null },
{ id: 2, name: 'Computers', parent_id: 1 },
{ id: 3, name: 'Laptops', parent_id: 2 },
{ id: 4, name: 'Smartphones', parent_id: 1 }
];
res.json(categories);
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Tree Diagram</title>
<script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
<div id="tree-container"></div>
<script>
async function fetchCategories() {
const response = await fetch('/api/categories');
return await response.json();
}
function buildTree(data, parentId = null) {
return data
.filter(item => item.parent_id === parentId)
.map(item => ({
...item,
children: buildTree(data, item.id)
}));
}
function renderTree(treeData) {
const treeLayout = d3.tree().size([400, 300]);
const root = d3.hierarchy(treeData[0]);
const treeData = treeLayout(root);
const svg = d3.select("#tree-container")
.append("svg")
.attr("width", 500)
.attr("height", 400);
const links = svg.selectAll(".link")
.data(treeData.links())
.enter().append("path")
.attr("class", "link")
.attr("d", d3.linkHorizontal()
.x(d => d.y)
.y(d => d.x));
const nodes = svg.selectAll(".node")
.data(root.descendants())
.enter().append("g")
.attr("class", d => "node" + (d.children ? " node--internal" : " node--leaf"))
.attr("transform", d => `translate(${d.y},${d.x})`);
nodes.append("circle")
.attr("r", 4.5);
nodes.append("text")
.attr("dy", 3)
.attr("x", d => d.children ? -8 : 8)
.style("text-anchor", d => d.children ? "end" : "start")
.text(d => d.data.name);
}
fetchCategories().then(data => {
const treeData = buildTree(data);
renderTree(treeData);
});
</script>
</body>
</html>
id
和parent_id
。通过以上步骤和示例代码,你应该能够在JavaScript中成功读取数据库数据并生成树状图。
没有搜到相关的沙龙