HighCharts通过ajax加载数据

12

最近几天,我在使用Highcharts库将来自API的JSON数据通过Ajax填充到图表中时遇到了一些问题。

我在Ajax回调函数中尝试了chart.series[0].data = json等类似的操作,但是都没有起作用。

我的JSON数据是一个包含每天数据的数组。

"{"month_mentions_graphic":[521,49,81,0,101,0,0,0,21,3071,0,0,0,0,0,1479,6124,2409,2608,0,0,3457,2057,2580,5876,4638,0,0,3337,3479,430]}"

这是我的代码:

var chart;

$(document).ready(function() {

    chart = new Highcharts.Chart({
        chart: {
            renderTo: 'container',
            type: 'line',
            marginRight: 130,
            marginBottom: 25, 
            events: {
                load: requestData
            }
        },
        title: {
            text: 'Menções Mensais',
            x: -20 //center
        },
        xAxis: {
            categories: [1,2,3,4,5]
        },
        yAxis: {
            title: {
                text: 'Menções'
            },
            plotLines: [{
                value: 0,
                width: 1,
                color: '#808080'
            }]
        },
        legend: {
            layout: 'vertical',
            align: 'right',
            verticalAlign: 'top',
            x: -10,
            y: 100,
            borderWidth: 0
        },
        series: [
         {
            name: 'mentions',
            data: []
          }
        ]
    });
});


function requestData() {
    $.ajax({
        url: 'api/v1/dashboard/month_mention_graphic',
        type: "GET",
        dataType: "json",
        data : {username : "demo"},
        success: function(data) {
            chart.series[0].data = data;
        },
        cache: false
    });
}
1个回答

20

调用 chart.addSeries 一次性添加整个系列,而不是将点数组添加到初始的空系列中:

function requestData() {
    $.ajax({
        url: 'api/v1/dashboard/month_mention_graphic',
        type: "GET",
        dataType: "json",
        data : {username : "demo"},
        success: function(data) {
            chart.addSeries({
              name: "mentions",
              data: data.month_mentions_graphic
            });
        },
        cache: false
    });
}

谢谢,正是我寻找的。 - Rodrigo Dias

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接