Hari
Hari

Reputation: 23

struts2 iterator values into javascript array

Experts, I have a situation here. I have ArrayList of String[] (ArrayList of String arrays in Struts2 action class, I am iterating those values into javascript to pass those values as a two dimensional array to google graph by using

var twodarray = ["<s:iterator value='res' status='status'>[<s:property/>]<s:if test='#status.last==false'>,</s:if></s:iterator>"];

then passing that twodarray into google graph using

var data = google.visualization.arrayToDataTable(twodarray);

How google graph accepts the parameter is for example

var data = google.visualization.arrayToDataTable([
     ['Month', 'Electronic', 'Electric'],
     ['2017/03',  400,      290],
     ['2017/04',  450,      275]
  ]);

When I use

var data = google.visualization.arrayToDataTable(twodarray);

Graph is not showing up, but when I display the value of twodarray or alert the twodarray, it gives me the exact data as two dimensional array like below.

var twodarray=[['Month', 'Electronic', 'Electric'],['2017/03',  400,      290],['2017/04',  450,      275]];

I am wondering how the variable twodarray interprets value to pass as an 2D array to javascript function. Is it passing as a string? I am trying to pass it as a 2D array.

Upvotes: 2

Views: 1884

Answers (2)

fustaki
fustaki

Reputation: 1614

OK with Jan's solution. A suggestion, I would create the JS array in this way:

var twodarray = [];
<s:iterator value='res' status='status'>
    twodarray.push([<s:property/>]);
</s:iterator>

It makes it more readable in your template and in the HTML (no burdening coma conditions and nested brackets)

var twodarray = [];
twodarray.push(['Month', 'Electronic', 'Electric']);
twodarray.push(['2017/03',  400,      290]);
twodarray.push(['2017/04',  450,      275]);

Upvotes: 1

Jan
Jan

Reputation: 13858

Your variable declaration

var twodarray = ["<s:iterator value='res' status='status'>[<s:property/>]<s:if test='#status.last==false'>,</s:if></s:iterator>"];

contains " that are not required by the iterator - so they probably end up in your javascript-variable making it an array of strings - or an array with one string more exactly.

Removing the " should to the trick:

var twodarray = [<s:iterator value='res' status='status'>[<s:property/>]<s:if test='#status.last==false'>,</s:if></s:iterator>];

Upvotes: 1

Related Questions