我想绘制从MySQL数据库获取的一些值,并在单个页面中使用PHP和Chart.js。我尝试从这里提出建议:Chart with json data
这是我的代码:
<!DOCTYPE html>
<html>
<head>
<title>Demo Charts</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="vendor/jquery/jquery.min.js"></script>
<script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<!-- Core plugin JavaScript-->
<script src="vendor/jquery-easing/jquery.easing.min.js"></script>
<!-- Page level plugins -->
<script src="vendor/chart.js/Chart.min.js"></script>
</head>
<body>
<?php
error_reporting(E_ALL);
$conn = new mysqli('localhost', 'root', 'geo777', 'regime_shift');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$select_specie="Specia1";
//query to get data from the table
$query = 'SELECT AVG(`CARBON`) AS MedieCarbon, `Year` FROM `fpk20082018` where DENUM="'.$select_specie.'" GROUP BY `Year`';
//execute query
$result = $conn->query($query);
//loop through the returned data
$jsonfile = array();
foreach ($result as $row) {
$jsonfile[] = $row;
}
//free memory associated with result
$result->close();
//close connection
$conn->close();
$output = json_encode(['jsonarray' => $jsonfile]);
//now print the data
//print $output;
//var_dump($output);
?>
<div class="card-body">
<div class="chart-area">
<canvas id="canvas"></canvas>
</div>
</div>
</div>
<script type="text/javascript">
const useAJAX = false;
$(document).ready(function () {
if (useAJAX) $.getJSON('data_plot.php').then(showGraph);
else showGraph(<?= $output ?>);
});
function showGraph(data) {
console.log(data);
var labels = output.jsonarray.map(function(e) {
return e.Year;
});
var data = output.jsonarray.map(function(e) {
return e.MedieCarbon;
});
var ctx = canvas.getContext('2d');
var config = {
type: 'line',
data: {
labels: labels,
datasets: [{
label: 'Medie anuala Carbon',
data: data,
backgroundColor: "rgba(78, 115, 223, 0.05)",
borderColor: "rgba(78, 115, 223, 1)",
pointRadius: 3,
pointBackgroundColor: "rgba(78, 115, 223, 1)",
pointBorderColor: "rgba(78, 115, 223, 1)",
pointHoverRadius: 3,
pointHoverBackgroundColor: "rgba(78, 115, 223, 1)",
pointHoverBorderColor: "rgba(78, 115, 223, 1)",
pointHitRadius: 10,
pointBorderWidth: 2
}]
}
};
var chart = new Chart(ctx, config);
}
</script>
</body>
</html>
在控制台中,错误是:
未捕获的ReferenceError:未定义输出
jsonarray看起来像这样:
{
"jsonarray":[
{
"MedieCarbon":"0.5194997435897436",
"Year":"2008"
},
{
"MedieCarbon":"0.04090933333333334",
"Year":"2010"
},
{
"MedieCarbon":"0.01656",
"Year":"2011"
},
{
"MedieCarbon":"0.009573333333333335",
"Year":"2012"
},
{
"MedieCarbon":"0.020583333333333332",
"Year":"2017"
}
]
}
您已经将$output
定义为PHP中的变量,并正在尝试在JavaScript中使用它。那行不通。尝试在您的JavaScript中添加它:
var object = <?php echo json_encode($object); ?>;