0

I have written a JSP page:

<%
int var1 = 10;
int var2 = 20;
%>

<script>
function draw(){
var data = new google.visualization.DataTable();
data.addColumn('string', 'Category');    
              data.addColumn('number', 'Number');
              data.addRows([
                ['cat1', <%= var1 %>], ['cat2', <%= var2 %>]]);
}
</script>

It gives error when i use those variables in javascript function

var1 cannot be resolved to a variable

var2 cannot be resolved to a variable

Dax Amin
  • 497
  • 2
  • 5
  • 13

2 Answers2

0

Just use quotes like:

data.addRows([['cat1', "<%= var1 %>"], ['cat2', "<%= var2 %>"]]);

Single quotes should work as well:

data.addRows([['cat1', '<%= var1 %>'], ['cat2', '<%= var2 %>']]);
oberbics
  • 408
  • 4
  • 12
0

Your variable can be displayed like this:

"<%=var1%>"

Scriptlets are discouraged. Having said this, you can use a recommended approach like jstl. See below:

<c:set name="var1" value="10" />    
<c:set name="var2" value="20" />

Assign them:

  var value1 = "${var1}";
  var value2 = "${var2}";

Use them in your function:

 data.addRows([['cat1', "${var1}"], ['cat2', "${var2}"]]);

The article in the link below discusses the comparison of JSTL vs Scriplets:

Comparing JSTL and JSP Scriptlet Programming

Perdomoff
  • 938
  • 2
  • 7
  • 26