2017-07-26 48 views
0

當使用靜態數據,圓環圖顯示完美,例如:chart.js之甜甜圈不計算JSON數據正確

$.ajax({ 
     url: 'includes/stats.php?show', 
     dataType: 'json', 
     success: function (response) 
     { 
      console.log(response['CARS']); //I see 2 
      console.log(response['MOTORS']); //I see 0 
      console.log(response['BOATS']); //I see 0 
      var autoData = [ 
       { 
        value: 2, 
        color: "#4286f4", 
        highlight: "#4d6fa5", 
        label: "Cars" 
       }, 
       { 
        value: 0, 
        color: "#3fe276", 
        highlight: "#51a36d", 
        label: "Motor Homes" 
       }, 
       { 
        value: 0, 
        color: "#bde234", 
        highlight: "#87964e", 
        label: "Boats" 
       } 
      ]; 
      var ctx = document.getElementById("onChart").getContext("2d"); 
      var myNewChart = new Chart(ctx).Doughnut(autoData);     
     } 
}); 

我做的JSON調用,但回調,我填AUTODATA變量與靜態數據[2,0,0],這樣的圖表出現並計算100%的「汽車」,因爲它是唯一的一些值(2),其他人是0 ... 當我這樣做:

$.ajax({ 
     url: 'includes/stats.php?show', 
     dataType: 'json', 
     success: function (response) 
     { 
      console.log(response['CARS']); //I see 2 
      console.log(response['MOTORS']); //I see 0 
      console.log(response['BOATS']); //I see 0 
      var autoData = [ 
       { 
        value: response['CARS'], 
        color: "#4286f4", 
        highlight: "#4d6fa5", 
        label: "Cars" 
       }, 
       { 
        value: response['MOTORS'], 
        color: "#3fe276", 
        highlight: "#51a36d", 
        label: "Motor Homes" 
       }, 
       { 
        value: response['BOATS'], 
        color: "#bde234", 
        highlight: "#87964e", 
        label: "Boats" 
       } 
      ]; 
      var ctx = document.getElementById("onChart").getContext("2d"); 
      var myNewChart = new Chart(ctx).Doughnut(autoData);     
     } 
}); 

我得到的是什麼看起來像2%的圖表填充...這裏發生了什麼?

+0

請嘗試並查看此鏈接是否有幫助。 https://stackoverflow.com/questions/25665019/chart-js-doughnut-chart-not-properly-work – user8271644

+0

我已經看到了這個問題,我試着接受解決方案,但沒有成功(把數據變量作爲全局變量) ...現在我回到了問你的問題,我看到了一個評論,一個人說他使用PHP中的「intval」來創建數組...我試過了,它工作正常! :)我會在這裏回答這個問題。謝謝。 – user2864778

回答

0

我從PHP構建JSON,是這樣的:

$data = $autoQuery->fetch_array(); 
    $autoData = array('CARS' => $data['CARS'], 
        'MOTORS' => $data['MOTORS'], 
        'BOATS' => $data['BOATS']); 
    echo json_encode($autoData); 

這是行不通的。當我在每個$ data變量前放置intval()時,它就起作用了!