我试图使用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});
    });


图表应如下所示:
javascript - ChartJS AJAX加载标签和数据-LMLPHP

但是它生成如下:
javascript - ChartJS AJAX加载标签和数据-LMLPHP

我已经寻找解决方案,但找不到任何解决方案。在此先感谢您的帮助。

最佳答案

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

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

关于javascript - ChartJS AJAX加载标签和数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43530885/

10-10 01:58