我通过json_encode()得到一个数组,以使用jquery在chartjs中绘制条形图。但是,标签和数据显示为未定义。 console.log()正确显示json数组。
$arr = [
[
"Btype" => 1,
"amount" => 3
],
[
"Btype" => 2,
"amount" => 5
],
[
"Btype" => 3,
"amount" => 7
],
];
print json_encode($arr)
$(document).ready(function(){
$.ajax({
url:"http://localhost/scripts/draw.php",
method: "GET",
success: function(data){
console.log(data);
var b_type = [];
var number = [];
for(var i in data){
b_type.push("BT " + data[i].BType);
number.push(data[i].amount);
}
var chart = {
labels: b_type,
datasets: [
{
label: b_type,
backgroundColor: 'rgba(200,200,200,0.75)',
borderColor: 'rgba(200,200,200,0.75)',
hoverBackgroundColor: 'rgba(200,200,200,1)',
hoverBorderColor: 'rgba(200,200,200,1)',
data: number
}
]
};
var ctx = $("#myChart");
var barGraph = new Chart(ctx, {
type: 'bar',
data: chart
});
},
error: function(data){
console.log(data);
}
})
});
答案 0 :(得分:0)
您在这里有一个简单的错字:
b_type.push("BT " + data[i].BType);
data[i].BType
应该为data[i].Btype
(请注意t
中的小写Btype
)。
这是一个可行的示例(已删除AJAX代码):
let data = [{
"Btype": 1,
"amount": 3
}, {
"Btype": 2,
"amount": 5
}, {
"Btype": 3,
"amount": 7
}];
var b_type = [];
var number = [];
for (var i in data) {
// b_type.push("BT " + data[i].BType); // <-- typo: JSON has a lowercase "t"
b_type.push("BT " + data[i].Btype); // <-- fixed
number.push(data[i].amount);
}
var chart = {
labels: b_type,
datasets: [{
label: b_type,
backgroundColor: 'rgba(200,200,200,0.75)',
borderColor: 'rgba(200,200,200,0.75)',
hoverBackgroundColor: 'rgba(200,200,200,1)',
hoverBorderColor: 'rgba(200,200,200,1)',
data: number
}]
};
var ctx = $("#myChart");
var barGraph = new Chart(ctx, {
type: 'bar',
data: chart
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script>
<canvas id="myChart"></canvas>