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 inng as a String. Whatformat i have to use to get it as an array
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 inng as a String. Whatformat i have to use to get it as an array
Share Improve this question edited Oct 10, 2013 at 15:38 Álvaro González 147k45 gold badges279 silver badges377 bronze badges asked Jun 5, 2013 at 4:03 Veena SujithVeena Sujith 1851 gold badge5 silver badges16 bronze badges 3- 3 Java... you mean your page is written in JSP ? – Raptor Commented Jun 5, 2013 at 4:04
-
1
What about
"somestring,somethingelse".split(',')
? – NoBugs Commented Jun 5, 2013 at 4:06 - From Android Using WebView i have created the page and i want to send a String Array to Javascript to execute some mands. – Veena Sujith Commented Jun 5, 2013 at 4:11
3 Answers
Reset to default 2Two ideas e 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./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>