5

以下代码有效:

var options1 = {
    chart: {
        renderTo: 'container1'
    },
    series: [{}]
    };

$.getJSON('tokyo.jsn', function(data){
        options1.series[0].data = data;
        var chart = new Highcharts.Chart(options1);
    });

我希望能够添加一些数据系列,所以我试图从 getJSON 中引用“new Highcharts”,但我似乎没有做对。以下代码不起作用:

$.getJSON('tokyo.jsn', function(data){
    options1.series[0].data = data;
});
var chart = new Highcharts.Chart(options1);

我也尝试过以不同的方式解决它,但以下代码再次不起作用:

var chart1 = new Highcharts.Chart({
    chart: {
        renderTo: 'container1'
    },
    series: [{}]
});

$.getJSON('tokyo.jsn', function(data){
    chart1.series[0].data = data;
});

谁能指出我正确的方向。我需要能够通过执行第二个 getJSON 调用来支持多个数据系列,如下所示:

$.getJSON('sydney.jsn', function(data){
    options1.series[1].data = data;
});

我使用的 JSON 代码如下:

[ 7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6 ]

谢谢

4

2 回答 2

4

$.getJSON is an asynchronous request. Once you receive the data, then you can pass it to Highcharts, thus you have to call that code from within the callback function of $.getJSON().

Try this, use a helper function to process your data and draw the chart, see drawChart() below:

var options1 = {
    chart: {
        renderTo: 'container1'
    },
    series: []
};

var drawChart = function(data, name) {
    // 'series' is an array of objects with keys: 
    //     - 'name' (string)
    //     - 'data' (array)
    var newSeriesData = {
        name: name,
        data: data
    };

    // Add the new data to the series array
    options1.series.push(newSeriesData);

    // If you want to remove old series data, you can do that here too

    // Render the chart
    var chart = new Highcharts.Chart(options1);
};

$.getJSON('tokyo.jsn', function(data){
    drawChart(data, 'Tokyo');
});
$.getJSON('sydney.jsn', function(data){
    drawChart(data, 'Sydney');
});

See fiddle: http://jsfiddle.net/amyamy86/pUM7s/

于 2013-04-19T17:55:37.943 回答
4

您可以在该示例中使用 Highcharts 使用的解决方案:http ://www.highcharts.com/stock/demo/compare

或者先创建空图表,没有任何系列,然后addSeries()在每个回调中使用函数,参见:http://api.highcharts.com/highcharts#Chart.addSeries()

于 2013-04-22T10:22:35.630 回答