简体   繁体   中英

Passing data to Google Chart API

Firstly, the Google Chart API example from Google (it is javascript) actually

<script type="text/javascript">
      // There is of coz some thing else but i just ignore them, just focus on the data here
      function drawChart() {
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Year');
        data.addColumn('number', 'Sales');
        data.addColumn('number', 'Expenses');
        data.addRows([
          ['2004', 1000, 400],
          ['2005', 1170, 460],
          ['2006', 660, 1120],
          ['2007', 1030, 540]
        ]);
    </script>

Now i modify to become this

<script type="text/javascript">
      function drawChart(reading) {
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Year');
        data.addColumn('number', 'Sales');
        data.addColumn('number', 'Expenses');
        data.addRows([reading]);
    </script>

(I implement in servlet) Now, i wish to pass my own data ( after reading from database) and make it to a string. pass it to the modified javascript by calling drawChart(reading)

//After some action retrieving data from db and make it to a data string like this
        String reading = "['2011',1000,400],['2009',800,200]";
        out.println("<body onload=\"drawChart("+reading");\">");
            //drawing is here
            out.println("</body>");

However, it seems that JS can't accept such string variable, what kind of format should i pass the variable to the JS? Or i shouldn't use String reading but others? But there isn't such kind of variable type in Java..

Just let Java print exactly the same data as you would write in plain vanilla JavaScript. You do not need to convert the data at all. Java doesn't execute JavaScript. Java just generates JavaScript code which get executed later when arrived at webbrowser.

String reading = "[['2004', 1000, 400],['2005', 1170, 460],['2006', 660, 1120],['2007', 1030, 540]]";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM