我正在尝试使用数据库数据从canvasjs创建行garph。但是我将数据传递给数据点时遇到了问题。
$.ajax({
dataType : "json",
type: "POST",
url: base_url + 'index.php/dashboard/line_graph',
data: {},
success: function(data)
{
for(var i = 0; i < data.length; i++)
{
var firstdate = data[i].nextdate;
var res = firstdate.replace(/[-]/g,',');
fd += '{ x: new Date(' + res + '), y:' + data[i].count +'},';
}
var fin = fd.slice(0,-1);
finals = "[" + fin + "]";
var chart = new CanvasJS.Chart("chartContainer",
{
title:{
text: "Booking - per month (DEMO)"
},
data: [
{
type: "line",
dataPoints: finals
}
]
});
chart.render();
}
});
当我发出警告finals
并将警报数据复制粘贴到数据点并运行然后运行时。但是当包含相同数据的变量传递给datapoint时,它就不起作用了。
在控制台日志中,我收到此错误。
TypeError: l.dataPoints[q].x is undefined
数据点的格式是这样的。当我发出警报时,变量finals
也包含相同的数据。
[
{ x: new Date(2015,03,6), y:4},
{ x: new Date(2015,03,11), y:0},
{ x: new Date(2015,03,16), y:0},
{ x: new Date(2015,03,21), y:0},
{ x: new Date(2015,03,26), y:0},
{ x: new Date(2015,03,31), y:14}
]
我的页面返回此json_encode格式。
[
{"firstdate":"2015-03-01","nextdate":"2015-03-6","count":"4"},
{"firstdate":"2015-03-6","nextdate":"2015-03-11","count":"0"},
{"firstdate":"2015-03-11","nextdate":"2015-03-16","count":"0"},
{"firstdate":"2015-03-16","nextdate":"2015-03-21","count":"0"},
{"firstdate":"2015-03-21","nextdate":"2015-03-26","count":"0"},
{"firstdate":"2015-03-26","nextdate":"2015-03-31","count":"14"}
]
我没有得到问题。请帮助。
答案 0 :(得分:4)
您不必像字符串那样创建finals
变量,您可以直接使用Javascript的对象格式:
$.ajax({
type: "POST",
url: base_url + 'index.php/dashboard/line_graph',
data: {},
success: function(data)
{
var tabData = JSON.parse(data);
var finals = [];
for(var i = 0; i < tabData.length; i++)
{
var firstdate = tabData[i].nextdate;
var res = firstdate.split('-');
finals.push({ 'x': new Date(res[2],res[1],res[0]), 'y': tabData[i].count });
}
var chart = new CanvasJS.Chart("chartContainer",{
title:{
text: "Booking - per month (DEMO)"
},
data: [
{
type: "line",
dataPoints: finals
}
]
});
chart.render();
}
});
答案 1 :(得分:1)
不要把所有东西都用字符串创建:
var finals = [];
for(var i = 0; i < data.length; i++)
{
var firstdate = data[i].nextdate;
var res = firstdate.replace(/[-]/g,',');
finals.push({ x: new Date(res), y: parseInt(data[i].count)});
}
答案 2 :(得分:0)
您可以使用php变量的循环在视图中构建数组数据,例如:
<script type="text/javascript">
var current_month = [];
<?php foreach ($grafico_current as $key => $value) { ?>
current_month.push({ 'x': new Date(<?php echo $value['ano']; ?>,<?php echo $value['mes']; ?>,<?php echo $value['dia']; ?>), 'y': <?php echo $value['total']; ?> });
<?php } ?>
</script>
之后,使用此新变量设置dataPoint:
数据点:当前月
答案 3 :(得分:-1)
传递数据 dataPoints:JSON.parse(data)
而不是 dataPoints:data