0

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

3
  • 3
    Java... you mean your page is written in JSP ? Commented Jun 5, 2013 at 4:04
  • 1
    What about "somestring,somethingelse".split(',') ? 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 commands. Commented Jun 5, 2013 at 4:11

3 Answers 3

2

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>
Sign up to request clarification or add additional context in comments.

1 Comment

I thought you were developing for a jsp page. Please ignore this post if you are not looking for this.
1

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

Comments

0
<%
    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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.