12

In my Java code, I have an ArrayList of Strings. 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?

4

5 回答 5

13

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) %>;
于 2013-07-03T06:01:34.090 回答
5

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

于 2013-07-03T05:15:57.523 回答
2

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 = [];
于 2013-08-20T23:12:32.223 回答
2

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(",");
}
于 2014-09-14T12:27:36.493 回答
1

try this way:

var myArray = <%=net.sf.json.JSONSerializer.toJSON(arrayList) %>;
于 2013-07-03T05:59:53.160 回答