Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass Java array contents into javascript array?

<%
    //Retrieving the Server list from dispatcher
    Collection<Server> svr = (Collection<Server>)request.getAttribute("stuff");

    ArrayList<String> serverIds = new ArrayList<String>();

    for(Server i : svr )
      serverIds.add(i.getId());

    String [] svrIds = new String[svr.size()];
    serverIds.toArray(svrIds);

%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript">

    var instanceIds = new Array(<%=svrIds%>);

    //test somethings in there
    alert(instanceIds[0]);


</script>
</head>
</html>
like image 729
stackoverflow Avatar asked Mar 15 '26 21:03

stackoverflow


2 Answers

If you want to use Java code to write the code for a Javascript data structure, probably the simplest way to do it is to use a JSON library for Java. A JSON string can be interpreted as Javascript code.

If you want to use JSON.simple, then there are examples here of how to generate the JSON string:

http://code.google.com/p/json-simple/wiki/EncodingExamples

In your code, you should be able to do something like this:

var instanceIds = <%= JSONValue.toJSONString(serverIds) %>

You shouldn't need to convert your ArrayList to a Java array. Note that this function is sensitive to what type you pass into it; an array actually won't work in this instance.

Also, to do this you will need to install the JSON.simple JAR file and import org.json.simple.JSONValue in your JSP.

like image 78
Nate C-K Avatar answered Mar 18 '26 11:03

Nate C-K


<%
    String[] jArray= new String[2];
    jArray[0]="a";
    jArray[1]="b";

    StringBuilder sb = new StringBuilder();
    for(int i=0;i<jArray.length;i++) 
        sb.append(jArray[i]+",");
%>

<script type="text/javascript">
    temp="<%=sb.toString()%>";
    var strr = new Array();
    strr = temp.split(',','<%=jArray.length%>');

    alert("array: "+strr);
</script>
like image 26
Amin Sh Avatar answered Mar 18 '26 11:03

Amin Sh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!