gpt4 book ai didi

jquery - Chartjs 条形图显示未定义的值

转载 作者:行者123 更新时间:2023-12-01 05:13:17 24 4
gpt4 key购买 nike

我通过 json_encode() 获取一个数组,以使用 jquery 在 Chartjs 中绘制条形图。但是标签和数据显示为未定义。 console.log() 正确显示 json 数组。

条形图: example of incorrect chart

控制台日志: console log showing json output

$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);
}
})
});

最佳答案

这里有一个简单的拼写错误:

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>

关于jquery - Chartjs 条形图显示未定义的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57434467/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com