Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 716
08091 Yin Avatar asked Mar 19 '26 18:03

08091 Yin


1 Answers

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]]";
like image 184
BalusC Avatar answered Mar 21 '26 09:03

BalusC