且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

通过AJAX HighCharts加载数据

更新时间:2023-12-05 08:43:28

呼叫chart.addSeries添加整个系列中一气呵成,仅仅加入了点阵列初始空系列,而不是:

 函数的RequestData(){
    $阿贾克斯({
        网址:API / V1 /仪表板/ month_mention_graphic',
        键入:GET,
        数据类型:JSON,
        数据:{用户名:演示},
        成功:功能(数据){
            chart.addSeries({
              名称:提到
              数据:data.month_mentions_graphic
            });
        },
        缓存:假的
    });
}
 

I have been encountering issues for the past few days with ajaxing in some sample json data from an api to populate a chart using the Highcharts library.

I tried to chart.series[0].data = json and similar stuff in my ajax callback but nothing works.

my json is an array of data for each day in the month.

"{"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]}"

Here's my code:

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
    });
}

Call chart.addSeries to add the whole series in one go instead of adding just the point array to the initial empty series:

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
    });
}