Reputation: 185
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
Upvotes: 0
Views: 16082
Reputation: 2814
<%
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>
Upvotes: 0
Reputation: 5554
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>
Upvotes: 2
Reputation: 6973
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
Upvotes: 1