0

I am using the following snippet to populate a Google Chart-

<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>

This works a treat and creates a line graph as desired.

However I wish to pass data to this function from my code behind -

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

             }
}

And then use is like -

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

Where count and category are the X and Y axis values and the 17167,18183 etc are the points on the graph. However clearly the aforementioned syntax is incorrect, how can I modify the function to accept my Json data?

4

1 回答 1

0

Since you already have the JSON string, there's no point in parsing it, then re-serializing it. Just inject it directly, and use Javascript to map into the Google Viz format:

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 is demo of the data-mapping part.

于 2013-10-16T17:24:22.793 回答