2017-03-07 53 views
-1

您好我得到我的數據與阿賈克斯,他們是使用JSON來了,所以我的代碼是這樣如何在這裏使用for循環?

$.ajax({ 
     async:true, 
     type: "POST", 
     dataType: "html", 
     contentType: "application/x-www-form-urlencoded", 
     url:"http://sosacelulares.com/index.php/chart/buygeneralreport", 
     success: function(response) { 
     var returnedData = JSON.parse(response); 

的數據看起來像這樣

[{ 
    "id_buy_report":"1", 
    "month":"1", 
    "year":"2016", 
    "total":"10" 
},{ 
    "id_buy_report":"2", 
    "month":"1", 
    "year":"2017", 
    "total":"20" 
}] 

然後我試圖使用這些數據創建一個餅圖和完整的代碼是這樣的:

$.ajax({ 
     async:true, 
     type: "POST", 
     dataType: "html", 
     contentType: "application/x-www-form-urlencoded", 
     url:"http://sosacelulares.com/index.php/chart/buygeneralreport", 
     success: function(response) { 
     var returnedData = JSON.parse(response); 

     var donutData = [ 
     {label: "Series2", data: 10}, 
     {label: "Series3", data: 40}, 
     {label: "Series4", data: 50} 
     ]; 

     $.plot("#donut-chart", donutData, { 
     series: { 
      pie: { 
      show: true, 
      radius: 1, 
      innerRadius: 0.5, 
      label: { 
       show: true, 
       radius: 2/3, 
       formatter: labelFormatter, 
       threshold: 0.1 
      } 

      } 
     }, 
     legend: { 
      show: false 
     } 
     }); 

的問題是,我的數據來了,你怎麼可以從數據庫中看到,如果我想創建餅圖我這裏需要把數據..

var donutData = [ 
    {label: "Series2", data: 10}, 
    {label: "Series3", data: 40}, 
    {label: "Series4", data: 50} 
    ]; 

這將創建一個餅圖有三個部分,但它是靜態的我需要把A(for循環),以使數據全自動創建..

如何在donutData代碼中創建for循環?任何循環都沒有必要for循環..我只需要一個循環,它允許我自動填充donutData。由於

+0

'數據類型: 「HTML」'< - 什麼? – Phil

回答

0

只需使用一個foreach循環通過它,就像這樣:

var donutData = [ 
    {label: "Series2", data: 10}, 
    {label: "Series3", data: 40}, 
    {label: "Series4", data: 50} 
]; 

donutData.forEach(function(data) { 
    console.log(data.label); 
    console.log(data.data); 
});