HighCharts 通过 ajax 加载数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13157693/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 10:51:50  来源:igfitidea点击:

HighCharts load data via ajax

ajaxhighcharts

提问by Rodrigo Dias

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.

在过去的几天里,我在使用 Highcharts 库对来自 api 的一些示例 json 数据进行 ajaxing 以填充图表时遇到了问题。

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

我试图在我的 ajax 回调中使用 chart.series[0].data = json 和类似的东西,但没有任何效果。

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

我的 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]}"

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

回答by Greg Ross

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

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