In my Java code, I have an ArrayList
of String
s. I'd like to put this data in a JavaScript variable on a JSP page I'm working on. My first thought was to include it directly, e.g.:
var myArray = <%= arrayList %>;
Unfortunately, when executed, myArray
is a string in the format [a,b,c]
, not an actual JavaScript array. How do I get some data from a Java ArrayList
to a JavaScript array?
The JavaScript split() method returns an array, so it's a simple way to convert a Java ArrayList into a JavaScript array.
function toJavascript(){
var array="<%=javaArrayList%>";
array=array.replace("[", "");
array=array.replace("]", "");
return javaArray.split(",");
}
Withoug a library:
Java:
public static String toJavascriptArray(String[] arr){
StringBuffer sb = new StringBuffer();
sb.append("[");
for(int i=0; i<arr.length; i++){
sb.append("\"").append(arr[i]).append("\"");
if(i+1 < arr.length){
sb.append(",");
}
}
sb.append("]");
return sb.toString();
}
JSP:
var myArray = <%= toJavascriptArray(arrayList) %>;
When you use <%=arraylist%>
it calls the toString()
on list and prints [a,b,c]
And No,you cannot direclty convert From Java arrayList
to javascript array ,Convert the Java ArrayList
to JSON String
, and use JSON.parse()
to get Javascript object
.
Have a look at Json objet and Json in java
Do the following in your JSP page
<% List<String> strList = new ArrayList<String>();
strList.add("one");
strList.add("two");
strList.add("three"); %>
var jsArray = [<% for (int i = 0; i < strList.size(); i++) { %>"<%= strList.get(i) %>"<%= i + 1 < strList.size() ? ",":"" %><% } %>];
The output will be
var jsArray = ["one","two","three"];
If your List was empty it will output
var jsArray = [];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With