Passing data to the Google Chart API
First, the Google Chart API example from Google (this is javascript) is 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 will change 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 am implementing in a servlet) Now, I want to pass my data (after reading from the database) and render it to a string. pass it to modified javascript by calling drawChart (read)
//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 looks like JS cannot accept a string variable like this, what format should the JS variable pass? Or should I not use line reading while others? But there is no such type of variables in Java.
+3
source to share
1 answer
Just let Java print exactly the same data as in plain vanilla JavaScript. You don't need to transform data at all. Java does not execute JavaScript. Java just generates JavaScript code that runs later when you get to the webbrowser.
String reading = "[['2004', 1000, 400],['2005', 1170, 460],['2006', 660, 1120],['2007', 1030, 540]]";
+1
source to share