简体   繁体   中英

How to pass array from java to javascript

I want to pass a String Array From java to javascript. How can i acheive the same. using loadUrl, i am passing the Java String [] to a javascript Function. (String[] StringName--> ["hello", "hi"])

But when i try to access the same in javascript

function displayString(StringName) {
    for(var i=0;i<StringName.length;i++) {
         alert("path : " + StringName[i]);
    }
}

i am expecting length to be 2 as there are only 2 items in the Java String[]. But in javascript it is cominng as a String. Whatformat i have to use to get it as an array

Two ideas come to my mind. You can create a javascript array using jsp or you can use a separator for the java array and create into a string, then read back in javascript using split() on the string.

Method 1:

<% String array[] = // is your initialized array %>

<script>
var jsArray = new Array();
<% for(String element:array){
%> jsArray[jsArray.length] = <% element %>
<% } %>
</script>

This should create a ready to use Javascript array with the values contained in your Java array.

Method 2: (Using separator as #)

<% StringBuilder sb = new StringBuilder();
for(String element:array){
sb.append(element + "#");
}
%>
<script>
var temp = <% sb.toString() %>
var array = temp.split('#');
...
</script>

Java to JSON and JSON to Java is fairly well covered ground.

you should check this out.

https://stackoverflow.com/questions/338586/a-better-java-json-library

<%
    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 array = new Array();
    array = temp.split(',','<%=jArray.length%>');

    alert("array: "+array);
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM