ChartJS AJAX加载标签和数据

时间:2017-04-20 22:23:10

标签: javascript jquery json ajax chart.js

我试图使用AJAX将标签和数据加载到ChartJS中。

使用

的JSON文件
{
"trendingLineChartLabels": "['JAN','FEB','MAR']",
"trendingLineChartData": "[1, 5, 2]"
}

jQuery代码

$.getJSON("test.json", function(response) { 
    console.log(JSON.stringify(response.trendingLineChartLabels));
    var trendingLineChartData = {
        labels : response.trendingLineChartLabels,
        datasets : [
            {
                label: "First dataset",
                fillColor : "rgba(128, 222, 234, 0.6)",
                strokeColor : "#ffffff",
                pointColor : "#00bcd4",
                pointStrokeColor : "#ffffff",
                pointHighlightFill : "#ffffff",
                pointHighlightStroke : "#ffffff",
                data: response.trendingLineChartData
            }
        ]
    }, trendingLineChart = document.getElementById("trending-line-chart").getContext("2d"); 
    window.trendingLineChart = new Chart(trendingLineChart).Line(trendingLineChartData, {scaleShowGridLines:!0,scaleGridLineColor:"rgba(255,255,255,0.4)",scaleGridLineWidth:1,scaleShowHorizontalLines:!0,scaleShowVerticalLines:!1,bezierCurve:!0,bezierCurveTension:.4,pointDot:!0,pointDotRadius:5,pointDotStrokeWidth:2,pointHitDetectionRadius:20,datasetStroke:!0,datasetStrokeWidth:3,datasetFill:!0,animationSteps:15,animationEasing:"easeOutQuart",tooltipTitleFontFamily:"'Roboto','Helvetica Neue', 'Helvetica', 'Arial', sans-serif",scaleFontSize:12,scaleFontStyle:"normal",scaleFontColor:"#fff",tooltipEvents:["mousemove","touchstart","touchmove"],tooltipFillColor:"rgba(255,255,255,0.8)",tooltipTitleFontFamily:"'Roboto','Helvetica Neue', 'Helvetica', 'Arial', sans-serif",tooltipFontSize:12,tooltipFontColor:"#000",tooltipTitleFontFamily:"'Roboto','Helvetica Neue', 'Helvetica', 'Arial', sans-serif",tooltipTitleFontSize:14,tooltipTitleFontStyle:"bold",tooltipTitleFontColor:"#000",tooltipYPadding:8,tooltipXPadding:16,tooltipCaretSize:10,tooltipCornerRadius:6,tooltipXOffset:10,responsive:!0});            
    });

图表应如下所示: enter image description here

但它产生如下: enter image description here

我已经搜索了解决方案,但无法找到任何解决方案。提前感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

您的 JSON 对象无效,应该是这样的......

{
    "trendingLineChartLabels": ["JAN", "FEB", "MAR"],
    "trendingLineChartData": [1, 5, 2]
}