javascript 如何将数组从java传递给javascript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16931350/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 06:30:33  来源:igfitidea点击:

How to pass array from java to javascript

javajavascript

提问by Veena Sujith

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"])

我想将字符串数组从 java 传递给 javascript。我怎样才能达到同样的目标。使用 loadUrl,我将 Java 字符串 [] 传递给 javascript 函数。(String[] StringName--> ["hello", "hi"])

But when i try to access the same in javascript

但是当我尝试在 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

我期望长度为 2,因为 Java String[] 中只有 2 个项目。但在 javascript 中,它是作为字符串出现的。我必须使用什么格式才能将其作为数组

回答by midhunhk

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.

我想到了两个想法。您可以使用 jsp 创建一个 javascript 数组,或者您可以使用 java 数组的分隔符并创建一个字符串,然后在字符串上使用 split() 在 javascript 中读回。

Method 1:

方法一:

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

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

这应该使用 Java 数组中包含的值创建一个随时可用的 Javascript 数组。

Method 2: (Using separator as #)

方法2:(使用分隔符作为#)

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

回答by madmik3

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

Java to JSON 和 JSON to Java 是相当广泛的领域。

you should check this out.

你应该检查一下。

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

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

回答by Amin Sh

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