使用Chart.js折线图展示MySQL温度数据失败,求助实现方法
Hey there, I totally get how frustrating it is to spend a week stuck on this—let’s get your line chart working step by step. Here’s a complete, straightforward solution tailored to your setup:
Step 1: Set Up Your HTML Structure
First, you’ll need a canvas element where Chart.js will render the chart, plus include the Chart.js library (make sure you’ve downloaded it and placed it in your project folder, or use a local copy):
<!DOCTYPE html> <html> <head> <title>Temperature Line Chart</title> <!-- Include your local Chart.js file --> <script src="chart.umd.js"></script> <!-- Use the correct filename for your Chart.js version --> </head> <body> <!-- Canvas container for the chart --> <canvas id="temperatureChart" width="800" height="400"></canvas> <script> // Your chart logic will go here </script> </body> </html>
Step 2: Fetch & Prepare Data from getdata.php
Use JavaScript’s fetch() API to grab your JSON data, then transform it into the format Chart.js needs. Note that we’ll convert the temperature string to a number—this is a common pitfall!
// Grab the canvas context const ctx = document.getElementById('temperatureChart').getContext('2d'); // Fetch data from your PHP endpoint fetch('getdata.php') .then(response => { // Check if the request succeeded if (!response.ok) throw new Error('Failed to load data'); return response.json(); }) .then(rawData => { // Extract dates and temperatures into separate arrays const chartLabels = rawData.map(item => item.date); const temperatureData = rawData.map(item => parseFloat(item.temp)); // Initialize the line chart new Chart(ctx, { type: 'line', data: { labels: chartLabels, datasets: [{ label: 'Temperature (°C)', data: temperatureData, borderColor: 'rgb(75, 192, 192)', backgroundColor: 'rgba(75, 192, 192, 0.1)', tension: 0.1, fill: true }] }, options: { scales: { x: { type: 'time', // Tell Chart.js this is time-based data time: { unit: 'hour', // Adjust based on your data frequency (day/minute/etc.) tooltipFormat: 'YYYY-MM-DD HH:mm' // Format for hover tooltips }, title: { display: true, text: 'Date & Time' } }, y: { title: { display: true, text: 'Temperature (°C)' }, beginAtZero: false // Disable if your temps never hit zero } }, responsive: true, maintainAspectRatio: false } }); }) .catch(error => { console.error('Error:', error); alert('Failed to load temperature data—check your browser console for details.'); });
Quick Troubleshooting Tips
- Validate your PHP output: Visit
getdata.phpdirectly in your browser to confirm it returns valid JSON (no extra HTML/errors mixed in). - Check Chart.js loading: Double-check the filename in your script tag—modern Chart.js versions use
chart.umd.jsfor browser environments. - Adjust time axis units: If dates look messed up, tweak the
unitvalue in the x-axis options (e.g., use 'day' for daily data, 'minute' for frequent readings).
That should get your chart up and running! If you still hit snags, your browser’s developer tools (F12) will show specific error messages to help narrow down the issue.
内容的提问来源于stack exchange,提问作者Tomas Hylander

