2014-02-16 24 views
-1

數據值我使用的是highcharts.js庫來爲我的網站 我有一個數組,其值從我從我的服務器的Ajax響應得的利潤損失&圖。使用數組作爲Highcharts.js

這是代碼:

<script type="text/javascript"> 
var profit = []; 
$(document).ready(function(e) { 
     $.ajax({ 
     url : "/php/get-inflow.php", 
     dataType: "json", 
     type: "POST", 
     success: function(data){ 
      for(var i =0; i<data.length; i++){ 
       if(data[i] == null){ 
        profit[i] = 0; 
      }else{ 
        profit[i] = data[i]; 
       } 
      } 
     } 
    }); 
}); 
$(function() { 
    $('#profitloss').highcharts({ 
//some other highcharts code 
series: [{ 
       name: 'Inflow', 
       data: profit 
      }, { 
       name: 'Outflow', 
       data: [2, 2, 3, 2, 1,10,10,10,10,10,10,10] 
      }] 
     }); 
    }); 
</script> 

我認爲陣列(利潤[])無法識別,或者這是不是一個有效的方法是什麼?謝謝!

回答

2

因爲AJAX調用是異步的,profit陣列仍然是空的(定義爲[])被顯示圖表時。你必須移動的圖表創建代碼AJAX success()功能,如:

$(document).ready(function(e) { 
     $.ajax({ 
     url : "/php/get-inflow.php", 
     dataType: "json", 
     type: "POST", 
     success: function(data){ 
      for(var i =0; i<data.length; i++){ 
       if(data[i] == null){ 
        profit[i] = 0; 
      }else{ 
        profit[i] = data[i]; 
       } 
      } 

      $('#profitloss').highcharts({ 
       //some other highcharts code 
       series: [{ 
        name: 'Inflow', 
        data: profit 
       }, { 
        name: 'Outflow', 
        data: [2, 2, 3, 2, 1,10,10,10,10,10,10,10] 
       }] 
      }); 
     } 
    }); 
}); 

另一種選擇是讓該繪製圖表功能:

function drawChart() { 
    $('#profitloss').highcharts({ 
     series: [{ 
      name: 'Inflow', 
      data: profit 
     }, { 
      name: 'Outflow', 
      data: [2, 2, 3, 2, 1,10,10,10,10,10,10,10] 
     }] 
    }); 
} 

,並調用該函數後success()功能for循環:

success: function(data){ 
     for(var i =0; i<data.length; i++){ 
      if(data[i] == null){ 
       profit[i] = 0; 
      }else{ 
       profit[i] = data[i]; 
      } 
     } 
     drawChart(); 
    }