2013-10-16 209 views
0

我使用下面的片段來填充Google Chart -將數據傳遞給JavaScript函數

<script type="text/javascript"> 
    google.load("visualization", "1", { packages: ["corechart"] }); 
    google.setOnLoadCallback(drawChart); 
    function drawChart() { 
     var data = google.visualization.arrayToDataTable([ 
      ['Year', 'Sales', 'Expenses'], 
      ['2004', 1000, 400], 
      ['2005', 1170, 460], 
      ['2006', 660, 1120], 
      ['2007', 1030, 540] 
     ]); 

     var options = { 
      title: 'Company Performance' 
     }; 

     var chart = new google.visualization.LineChart(document.getElementById('chart_div')); 
     chart.draw(data, options); 
    } 
</script> 

這工作一種享受,並根據需要創建一個折線圖。

不過,我希望將數據從我的代碼傳遞給這個函數的背後 -

protected void Page_Load(object sender, EventArgs e) 
{ 
    string JsonString = "{'res':[{'category':'A','count':17167},{'category':'B','count':18183},{'category':'C','count':17972},{'category':'D','count':18539}]}"; 
    Jobj = JObject.Parse(JsonString); 

    // extract values from Json 
      foreach (var response in Jobj["res"]) 
      { 

       string category= (string)response["category"]; 
       int count = (int)response["count"]; 

       // put values into format that can be passed to the javascript function 

      } 
} 

然後用像 -

function drawChart() { 
    var data = google.visualization.arrayToDataTable([<%=Data Values%>]); 

countcategory是X軸和Y軸值和17167,18183 etc是圖上的點。 但是,顯然上述語法不正確,我如何修改函數來接受我的Json數據?

+0

找到[此處](https://developers.google.com/chart/interactive/docs/reference#DataTable)文檔有幫助嗎?它似乎描述你需要什麼...... – Floris

回答

0

由於您已經擁有JSON字符串,解析它並沒有意義,然後重新序列化它。只需直接注入它,並使用Javascript來映射到谷歌的Viz格式:

function drawChart() { 
    var json = <%= JsonString %>; 
    var arr = [ ["Category", "Count"] ]; 
    json.res.forEach(function(item) { 
     arr.push([ item.category, item.count ]); 
    }); 
    console.log(JSON.stringify(arr)); // [["Category","Count"],["A",17167],["B",18183],["C",17972],["D",18539]] 
    var data = google.visualization.arrayToDataTable(arr); 
} 

Here是數據映射部分的演示。

+0

清晰而高效的答案。榮譽。 – Ebikeneser