2016-12-10 17 views
1

我已經創建了返回這樣如何使用json數據作爲高圖餅圖?

Object 
negative:3 
neutral:3 
positive:94 

這是直接從console.log();數據的Ajax請求

我試着用這個數據來創建一個餅圖,但是當我嘗試不畫圖表和沒有任何東西顯示出來,除了信用和控制檯中沒有錯誤。但如果我手動輸入這樣的數據:

series: [{ 
      name: 'Brands', 
      data: [ 

       { name: 'Positive', y: 94 }, 
       { name: 'Negative', y: 3 }, 
       { name: 'Neutral', y: 3 }, 
      ] 
     }] 

它工作沒問題。

我的代碼是:

function pieChart(data) { 
    // Make monochrome colors and set them as default for all pies 
    Highcharts.getOptions().plotOptions.pie.colors = (function() { 
     var colors = [], 
      base = Highcharts.getOptions().colors[0], 
      i; 

     for (i = 0; i < 10; i += 1) { 
      // Start out with a darkened base color (negative brighten), and end 
      // up with a much brighter color 
      colors.push(Highcharts.Color(base).brighten((i - 3)/7).get()); 
     } 
     return colors; 
    }()); 

    // Build the chart 
    Highcharts.chart('pieChart', { 
     chart: { 
      plotBackgroundColor: null, 
      plotBorderWidth: null, 
      plotShadow: false, 
      type: 'pie' 
     }, 
     title: { 
      text: 'Browser market shares at a specific website, 2014' 
     }, 
     tooltip: { 
      pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>' 
     }, 
     plotOptions: { 
      pie: { 
       allowPointSelect: true, 
       cursor: 'pointer', 
       dataLabels: { 
        enabled: true, 
        format: '<b>{point.name}</b>: {point.percentage:.1f} %', 
        style: { 
         color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black' 
        } 
       } 
      } 
     }, 
     series: [{ 
      name: 'Brands', 
      data: data 
     }] 
    }); 
}; 
+0

你的json看起來如何?你需要從服務器返回json,或者在客戶端創建它。 –

+0

謝謝,響應正從服務器返回。 'console.log()'返回的數據輸出'Object {positive:94,negative:3,neutral:3}' – kevinabraham

+0

讓我們繼續這裏:http://chat.stackoverflow.com/rooms/130280/http-stackoverflow- COM-問題-5471291的JavaScript與 - jQuery的點擊和doubl –

回答

1

你使用ajax請求,服務器收到的響應是一個對象。

您只需要根據收到的響應創建一個json數組。

var object={'positive':94,'neutral':2,'negative':2}; 
var data=[]; 
for(i in object){ 
    data.push({"name":i,"y":object[i]}); 
} 

並將其設置爲highchart系列。

series: [{ 
     name: 'Brands', 
     data: data 
}]