使用HighCharts + Ajax的JSON数据映射问题

时间:2011-07-15 06:41:00

标签: ajax json highcharts

我有通过JSON返回的关注数据

{"rows":[{"Date":"07/10/2011","Value":1206,"Action":"Drink"},    
{"Date":"07/11/2011","Value":2288,"Action":"Pie"},
{"Date":"07/12/2011","Value":1070,"Action":"Drink"},
{"Date":"07/13/2011","Value":1535,"Action":"Beer"},
{"Date":"07/14/2011","Value":1721,"Action":"Drink"}],
"page":1,"total":1,"records":5}

我正在尝试将此数据与HighCharts一起使用,但有点困惑。

jQuery.ajax({
  url: fullPath + 'datamap',
  dataType: "json",
  type: 'POST',
  data: "{}",
  contentType: "application/json; charset=utf-8",
  success: function (data) {
       var lines = data.split('\n');
        $.each(lines, function(lineNo, line) {
            var items = line.split(',');
            var data = {};
            $.each(items, function(itemNo, item) {
                if (itemNo === 0) {
                    data.name = item;
                } else {
                    data.y = parseFloat(item);
                }
            });
            options.series[0].data.push(data);
        });
    // Create the chart
    var chart = new Highcharts.Chart(options);

  },
  cache: false
  });

我正在尝试绘制“日期”和“价值”?

1 个答案:

答案 0 :(得分:4)

据我了解,您需要使用Highcharts显示rows值。首先,您的初始数据将是:

var chartData = data.rows;

现在chartData只是一个对象数组。使用for循环迭代chartData,如下所示:

var seriesData = [];
for (var i = 0; i < chartData.length; i++)
{
    var x = new Date(chartData[i].Date).getTime();
    var y = chartData[i].Value;
    seriesData.push([x, y]);
}

在此循环之后,您将拥有可在Highcharts中使用的seriesData点阵列。现在只需渲染它:

var chart = new Highcharts.Chart({
    chart: {
        renderTo: 'chartContainer',
        defaultSeriesType: 'line'
    },

    xAxis: {
        type: 'datetime'
    },

    series: [{
        data: seriesData        
    }]
});

瞧!

测试:http://jsfiddle.net/ebuTs/8263/