2014-02-16 48 views
0

我正在使用Chart.JS(chartjs.org),我想使用Facebook喜歡計數作爲我的圖表數據。獲取Facebook贊成計數Chart.JS

我的餅圖工作確定這樣的:

<script> 
    var pieData = [ 
      { 
       value : 30, 
       color : "#f04124" 
      }, 
      { 
       value : 70, 
       color : "#fff" 
      } 

     ]; 

var myPie = new Chart(document.getElementById("chart_01").getContext("2d")).Pie(pieData); 

</script> 

我是想類似的東西,但它不工作。

<script> 
jQuery.getJSON('http://graph.facebook.com/mysiteforchartdata1?callback=?', function(data){ 
      var fb_count2 = data['likes'].toString(); 

      $('.facebook_likes').html(fb_count2); 
}); 
jQuery.getJSON('http://graph.facebook.com/mysiteforchartdata2?callback=?', function(data){ 
      var fb_count2 = data['likes'].toString(); 

      $('.facebook_likes').html(fb_count2); 
}); 

    var pieData = [ 
      { 
       value : fb_count1, 
       color : "#f04124" 
      }, 
      { 
       value : fb_count2, 
       color : "#fff" 
      } 

     ]; 

var myPie = new Chart(document.getElementById("chart_01").getContext("2d")).Pie(pieData); 

</script> 

我會感謝完整的代碼,因爲我是一個JavaScript的新手。 謝謝!

回答

0

$.getJSON異步工作,所以當你定義pieData時,變量fb_count1fb_count2還不存在。你必須做到以下幾點:

$.when(
jQuery.getJSON('http://graph.facebook.com/metallica?callback=?'), 
jQuery.getJSON('http://graph.facebook.com/ironmaiden?callback=?') 
).then(function(data1, data2){ 
fb_count1 = data1[0]['likes']; 
fb_count2 = data2[0]['likes']; 

console.log([fb_count1, fb_count2]); // you can see the variables are there 

var pieData = [ 
    { 
    value : fb_count1, 
    color : "#f04124" 
    }, 
    { 
    value : fb_count2, 
    color : "#fff" 
    } 
]; 

var myPie = new Chart(document.getElementById("chart_01").getContext("2d")).Pie(pieData); 
}); 

$.when是創建多個請求(或其他遞延行動)回調的便捷方式。如果只有一個請求,則可以正常分配回撥:

jQuery.getJSON('http://graph.facebook.com/metallica?callback=?', function(data){ 
    // now you can do things with data 
    // but remember that everything that operates on it should be here 
}) 
// ... and not here