我想在MySQL数据库中显示记录的行数,并在ChartJs中显示数字,但是从我的PHP脚本得到的结果看来,这些数字不能正确显示。
用于统计来自MySQL数据库的记录的PHP代码段(Users_Retrieval.php)
$JSON_Response = array();
//Counts the number of Reporters
$Reporter_Query = "SELECT User_ID FROM User WHERE User_Type = 0";
$Count_Reporter = mysqli_query($Connection, $Reporter_Query);
$Reporter_Total = mysqli_num_rows($Count_Reporter);
array_push($JSON_Response, $Reporter_Total);
//Counts the number of Firefighters
$Firefighter_Query = "SELECT User_ID FROM User WHERE User_Type = 1";
$Count_Firefighter = mysqli_query($Connection, $Firefighter_Query);
$Firefighter_Total = mysqli_num_rows($Count_Firefighter);
array_push($JSON_Response, $Firefighter_Total);
echo json_encode($JSON_Response);
当我打印json_encode的内容时,它会打印我期望的值,我认为我的PHP脚本没有问题。 json_encode的输出:[5,1]
JavaScript ChartJs代码
//Reporter_Result and Firefighter_Result is both initialized in 1. It will
//be changed once the retrieval of JSON is correct
var Reporter_Result = 1;
var Firefighter_Result = 1;
$.ajax({
url: "Users.php",
method: "GET",
success: function(response){
//alert(response);
var User = JSON.parse(response);
var Reporter_Result = text(User.reporter);
var Firefighter_Result = text(User.firefighter);
}
});
var myPieChart = new Chart(ctx, {
type: 'pie',
data: {
labels: ["Reporters", "Firefighters"],
datasets: [{
data: [Reporter_Result, Firefighter_Result],
backgroundColor: ['#007bff', '#dc3545'],
}],
},
});
我认为问题出在我的javascript文件中,它没有从我的 Users_Retrieval.php 接收到值,该值正确为 [5,1] (我的理论)以及我尝试访问javascript中JSON值的方式。
这是饼图的当前进度/输出,我将在其中插入结果:
问题/秒:
如何在Users_Retrieval.php中从JSON获取值?我在JavaScript中接收JSON值的实现是错误的吗?如何正确获取它们以便将值插入到饼图中?
答案 0 :(得分:1)
好吧,如果是我,我很想从这里开始:
SELECT User_Type
, COUNT(*) total
FROM User
GROUP
BY User_Type;
答案 1 :(得分:1)
我在这里看到的问题是这样:
var Reporter_Result = text(User.reporter);
var Firefighter_Result = text(User.firefighter);
您似乎正在引用命名值,但是在php代码(和输出)中,您使用的是有序数组。
您可以像这样在$JSON_Response
之前将json_encode
定义为键值数组:
//array_push($JSON_Response, $Reporter_Total); // not like this
$JSON_Response['reporter'] = $Reporter_Total;
然后您的js就可以工作
** OR **将js更改为:
//var Reporter_Result = text(User.reporter); // not like this
var Reporter_Result = text(User[0]);
---编辑
看到的问题要多得多-您正在通过AJAX获取结果,但是是线性创建饼图-因此,图表开始绘制时,(示例)Firefighter_Result
的值为默认值
尝试将您的代码更改为此:
var myPieChart;
$.ajax({
url: "Users.php",
method: "GET",
success: function(response){
//alert(response);
var User = JSON.parse(response);
var Reporter_Result = text(User.reporter);
var Firefighter_Result = text(User.firefighter);
myPieChart = new Chart(ctx, {
type: 'pie',
data: {
labels: ["Reporters", "Firefighters"],
datasets: [{
data: [Reporter_Result, Firefighter_Result],
backgroundColor: ['#007bff', '#dc3545'],
}],
},
});
}
});