Refresh Google Visualization on the fly

2019-02-27 19:03发布

I am currently creating a google chart via google visualization and I want to be able to refresh/update this chart on a button click. I've tried a lot of different ways to do this but none of it works so I'm looking for any suggestions that anybody can make. My current platform is ASP.net (with C#) and the google stuff is written in javascript/jquery (obviously). Thanks!

1条回答
等我变得足够好
2楼-- · 2019-02-27 19:53

Gviz has the option to populate charts with JSON data, so, you can do this with jquery easily enough simply by making a call to your server to get a new set of data, having it return JSON, then passing this to a function that draws your charts.

Your jquery/javascript wil look something like this:

    function drawMyChart(data) {
        // stuff to draw chart using the contents of data
        // data should be Gviz Data Table in JSON format
        // your server needs to output this
        var dt = new google.visualization.DataTable(data)
        // rest of your stuff, just like standard gviz
    }

    function makeAjaxCall() {
        $.ajax({
            url: '/path/to/data/json',
            sucess: drawMyChart(a),
            dataType: 'json' // this is important, have it interpreted as json
        });
    }
// html somewhere
<input type='button' onclick='makeAjaxCall()'>Go</input>

With regard to correctly formatting your JSON response, there are a couple of libraries out there to help you, though I don't know of anything specifically in the languages you mentioned. Here's one in python for example.

If you're struggling, you can just dump out all of your entries in an array as follows:

  [[name, age],[john, 25],[paul, 20]]

and use google.visualization.arrayToDataTable to interpret it when it arrives back from your server as JSON.

Hope that helps.

查看更多
登录 后发表回答