我有一个来自mysql数据库的json数据,我打算将其绘制在图中,但是利用给定的数据却遇到了这个问题。
我的观点。
我已经声明了一个全局变量
var data2 =''; var labels2 ='';
我来自数据库的数据很好
$。get(“ http://myurl/dashboard/numberabsencesgraph”,函数(数据){ 密码 }
问题,我被困在这里。
这是我的代码...
$(function () {
var data2 = '';
var labels2 = '';
$.get("http://myurl/dashboard/numberabsencesgraph", function(data){
//$(".numemployee").html(data.mycount);
// beepPop.play();
//$('.spinner-border').hide();
for(i=0; i<data.length; i++){
data2 += data[i].number+',';
labels2 += ' "'+data[i].absentThisDays+'",';
}
data2 = data2.replace(/,\s*$/, "");
// data2 content is [1,22,33,44]
labels2 = '['+labels2.replace(/,\s*$/, "")+']';
//labels2 content is ["somedate","somedate","somedate","somedate"]
// iwant to put this in label location below
var LINECHARTEXMPLE = $('#lineChartExample');
var lineChartExample = new Chart(LINECHARTEXMPLE, {
type: 'line',
options: {
legend: {labels:{fontColor:"#777", fontSize: 12}},
scales: {
xAxes: [{
display: true,
gridLines: {
color: '#fff'
}
}],
yAxes: [{
display: true,
ticks: {
max: 100,
min: 20
},
gridLines: {
color: '#fff'
}
}]
},
},
data: {
// labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
labels: /*label location here*/ ,
datasets: [
{
label: "Data",
fill: true,
lineTension: 0.3,
backgroundColor: gradient1,
borderColor: 'rgba(210, 114, 181, 0.91)',
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
borderWidth: 2,
pointBorderColor: gradient1,
pointBackgroundColor: "#fff",
pointBorderWidth: 2,
pointHoverRadius: 5,
pointHoverBackgroundColor: gradient1,
pointHoverBorderColor: "rgba(220,220,220,1)",
pointHoverBorderWidth: 2,
pointRadius: 1,
pointHitRadius: 10,
// data: [0, 50, 33, 71, 49, 55, 35, 40, 30, 50, 25, 40],
data: /*data2 location here*/,
spanGaps: false
}
]
}
});
},"json");
**strong text**
答案 0 :(得分:0)
您在这里做一些非常奇怪的事情
for(i=0; i<data.length; i++){
data2 += data[i].number+',';
labels2 += ' "'+data[i].absentThisDays+'",';
}
data2 = data2.replace(/,\s*$/, "");
// data2 content is [1,22,33,44] <---- A string!!!!
labels2 = '['+labels2.replace(/,\s*$/, "")+']';
// labels2 content is ... also a string
我们不会创建类似的数组。您创建的是一个字符串(看上去很像数组),但是图表将期望使用实际的数组或对象。
您需要做的是创建一个数组并推送到该数组。
var data2 = [];
var labels2 = [];
for(i=0; i<data.length; i++){
data2.push(data[i].number);
labels2.push(data[i].absentThisDays);
}
然后摆脱替换功能...
然后您可以在图表创建过程中简单地使用它
// ...
labels: labels2,
data: data2,
// ...
请注意,没有理由在$.get
之外创建变量