我正在使用数据库中的数据绘制饼图。我的数据库非常简单,但它的结构与我正在检查的所有示例都不同。因此,它看起来像这样:
id | food | tickets
1 | 300 | 50
我猜id列是不必要的,因为它不会有更多的记录。
数据.php
<?php
//setting header to json
header('Content-Type: application/json');
require_once "../polaczenie.php";
//get connection
$mysqli = @new mysqli($host,$db_user,$db_password,$db_name);
if(!$mysqli){
die("Connection failed: " . $mysqli->error);
}
//query to get data from the table
$query = sprintf("SELECT id,food, tickets FROM arch_kategorie ORDER BY id");
//execute query
$result = $mysqli->query($query);
//loop through the returned data
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
//free memory associated with result
$result->close();
//close connection
$mysqli->close();
//now print the data
print json_encode($data);
?>
当我通过localhost://data.php检查结果时,我看到了这个:[{“食物”:“300”,“门票”:“50”}]
现在是有问题的部分:
应用程序.php
$(document).ready(function(){
$.ajax({
url : "data.php",
type : "GET",
success : function(data){
console.log(data);
var food= [];
var tickets= [];
for(var i in data) {
food.push(data[i].food);
tickets.push(data[i].tickets);
}
var ctx1 = $("#chartcanvas-1");
var data = {
labels : ["food", "tickets"],
datasets : [{
label : "Result",
data : food, tickets
backgroundColor : [
"#DEB887",
"#A9A9A9"
],
borderColor : [
"#CDA776",
"#989898"
],
borderWidth : [1, 1]
}]
};
var options = {
title : {
display : true,
position : "top",
text : "Pie Chart",
fontSize : 18,
fontColor : "#111"
},
legend : {
display : true,
position : "bottom"
}
};
var chart1 = new Chart( ctx1, {
type : "pie",
data : data,
options : options
});
});
},
error : function(data) {
console.log(data);
}
});
当然还有html:
索引.html
<style type="text/css">
#chart-container {
width: 80%;
height: auto;
}
</style>
<div class="chart-container">
<div class="chart-container">
<canvas id="chartcanvas-1"></canvas>
</div>
</div>
1条答案
按热度按时间2lpgd9681#
首先,在 AJAX success函数中有变量
data
的第二个定义。函数参数(parameters)在函数中作为局部变量工作,这与在函数中用关键字let
定义它们的方式相同。第二,
datasets
中的data
必须是number[]
,而JSON中的值是字符串。第三,有一点我不清楚,因为在描述数据集时您写道:
我猜id列是不必要的,因为它不会有更多的记录。
但随后您在 AJAX success函数中处理
data
,因为它是一个多元素对象数组,即使用for
循环。因此,这取决于您希望使用哪种类型的数据来实现。一个简单的解决方案,使用SQL表中的一行,Ajax success函数将如下所示:如果从SQL表中提取了多行,则可以将每个数组对象(即包含
id
字段的SQL行用作label
)用作单独的数据集。由于datasets
是一个JSON对象数组,因此可以将初始的data
转换为以下形式: