因此,我有一个类似于以下代码:https://jsfiddle.net/canvasjs/zxrkh502/ 但是我需要从 ajax / json 中放入数据,而不是 randomData 函数。我该怎么办?
var dps = [];
var chart = new CanvasJS.Chart("chartContainer",
{
title: {
text: "Chart with Date Selector"
},
data: [
{
type: "line",
dataPoints: randomData(new Date(2017, 0, 1), 400)
}
]
});
chart.render();
etc...
谢谢!
答案 0 :(得分:0)
首先进行ajax调用,构建数据数组,
然后继续其余的代码。
请参阅以下代码段...
$.ajax({
url: 'http://get-data-url',
type: 'GET',
headers: {accept: 'application/json;odata=verbose;'}})
.done(drawChart)
.fail(function (jqXHR, status, errorThrown) {
console.log('problem loading data: ' + errorThrown);
});
function drawChart(data) {
var dps = [];
$.each(data, function (rowIndex, row) {
dps.push({
x: row.xValue,
y: row.yValue
});
});
var chart = new CanvasJS.Chart("chartContainer",
{
title: {
text: "Chart with Date Selector"
},
data: [
{
type: "line",
dataPoints: dps
}
]
});
chart.render();
var axisXMin = chart.axisX[0].get("minimum");
var axisXMax = chart.axisX[0].get("maximum");
$("#fromDate").val(CanvasJS.formatDate(axisXMin, "DD MMM YYYY"));
$("#toDate").val(CanvasJS.formatDate(axisXMax, "DD MMM YYYY"));
$("#fromDate").datepicker({dateFormat: "d M yy"});
$("#toDate").datepicker({dateFormat: "d M yy"});
$("#date-selector").change( function() {
var minValue = $( "#fromDate" ).val();
var maxValue = $ ( "#toDate" ).val();
if(new Date(minValue).getTime() < new Date(maxValue).getTime()){
chart.axisX[0].set("minimum", new Date(minValue));
chart.axisX[0].set("maximum", new Date(maxValue));
}
});
$(".period").click( function() {
var period = this.id;
var minValue;
minValue = new Date(axisXMax);
switch(period){
case "1m":
minValue.setMonth(minValue.getMonth() - 1);
break;
case "3m":
minValue.setMonth(minValue.getMonth() - 3);
break;
case "6m":
minValue.setMonth(minValue.getMonth() - 6);
break;
case "1y":
minValue.setYear(minValue.getFullYear() - 1);
break;
default:
minValue = axisXMin;
}
chart.axisX[0].set("minimum", new Date(minValue));
chart.axisX[0].set("maximum", new Date(axisXMax));
});
}