90 lines
2.8 KiB
HTML
90 lines
2.8 KiB
HTML
<!DOCTYPE html>
|
|
<html lang="en">
|
|
<head>
|
|
<meta charset="UTF-8">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
<title>动态订单柱状图</title>
|
|
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
|
|
<style>
|
|
canvas {
|
|
width: 100% !important;
|
|
height: 400px !important;
|
|
}
|
|
</style>
|
|
</head>
|
|
<body>
|
|
<h2>订单数量柱状图</h2>
|
|
<canvas id="orderChart"></canvas>
|
|
|
|
<script>
|
|
// 初始化图表数据
|
|
const ctx = document.getElementById('orderChart').getContext('2d');
|
|
const chartData = {
|
|
labels: [],
|
|
datasets: [{
|
|
label: '订单数量',
|
|
data: [],
|
|
backgroundColor: 'rgba(75, 192, 192, 0.6)', // 柱状图的颜色
|
|
borderColor: 'rgb(75, 192, 192)',
|
|
borderWidth: 1
|
|
}]
|
|
};
|
|
|
|
const config = {
|
|
type: 'bar', // 设置为柱状图
|
|
data: chartData,
|
|
options: {
|
|
responsive: true,
|
|
scales: {
|
|
x: {
|
|
type: 'category',
|
|
position: 'bottom',
|
|
},
|
|
y: {
|
|
beginAtZero: true,
|
|
ticks: {
|
|
stepSize: 1
|
|
}
|
|
}
|
|
}
|
|
}
|
|
};
|
|
|
|
const orderChart = new Chart(ctx, config);
|
|
|
|
// 获取数据并更新图表
|
|
function fetchDataAndUpdateChart() {
|
|
fetch('/api/orders-count')
|
|
.then(response => response.json())
|
|
.then(data => {
|
|
// 按照 order_name 分类,汇总 order_count 的数量
|
|
let orderNames = {};
|
|
data.forEach(order => {
|
|
const name = order.order_name;
|
|
const count = parseInt(order.order_count);
|
|
|
|
if (orderNames[name]) {
|
|
orderNames[name] += count;
|
|
} else {
|
|
orderNames[name] = count;
|
|
}
|
|
});
|
|
|
|
// 更新图表数据
|
|
chartData.labels = Object.keys(orderNames); // 使用订单名称作为X轴标签
|
|
chartData.datasets[0].data = Object.values(orderNames); // 使用订单数量作为Y轴数据
|
|
|
|
orderChart.update();
|
|
})
|
|
.catch(error => console.error('获取数据失败:', error));
|
|
}
|
|
|
|
// 每5秒更新一次图表数据
|
|
setInterval(fetchDataAndUpdateChart, 5000);
|
|
|
|
// 初始数据加载
|
|
fetchDataAndUpdateChart();
|
|
</script>
|
|
</body>
|
|
</html>
|