2011-07-15 50 views
1

JSON數據映射的問題,我必須通過JSON與HighCharts + Ajax的

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

我想表「日期」和「價值」?

回答

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

這個循環之後,你將有seriesData陣列,可Highcharts使用點。現在只需渲染它:

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

    xAxis: { 
     type: 'datetime' 
    }, 

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

瞧!

測試此項:http://jsfiddle.net/ebuTs/8263/

+0

非常感謝!只有一個問題 - 我想以'07/10/2011'等格式的日期作爲X軸?任何方式來編輯你的代碼來做到這一點? – Tom

+0

http://jsfiddle.net/ebuTs/8277/ –

+0

哇!真棒謝謝:)我最後和最後一個問題[和不朽的感謝:)]是如何得到這個作爲ajax請求?即只是插入這個成功:函數(數據){' – Tom