将数组从 .jsp 传递给 javascript 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16731041/
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 05:46:42  来源:igfitidea点击:

Passing array from .jsp to javascript function

javascripthtmljspliferayportlet

提问by Smajl

I have a Liferay portlet where I pass a String array from action phase to render phase in my .jsp file. I am able to access the array and iterate through it like this:

我有一个 Liferay portlet,我将一个字符串数组从操作阶段传递到我的 .jsp 文件中的呈现阶段。我能够访问数组并像这样遍历它:

<c:forEach var="item" items="${arrayItems}"> 
    <p>${item}</p>
</c:forEach> 

This is just to check that passing the data works fine... However, I would like to pass this whole array to my javascript function (that handles rendering the data to canvas). Any idea how to do this?

这只是为了检查传递数据是否正常工作......但是,我想将整个数组传递给我的 javascript 函数(处理将数据渲染到画布)。知道如何做到这一点吗?

So far, I have tried the following:

到目前为止,我已经尝试了以下方法:

<%

String[] items;
items = new String[((String[])request.getAttribute("arrayItems")).length];
items = ((String[])request.getAttribute("arrayItems"));

%>

<script>
    displayItems(<% arrayItems %>);
</script>

and also

并且

<script>
        displayItems(${arrayItems});
</script>

I know that this is probably very basic question, but there are not many tutorials about passing data in portlets on web (and when I found any, the approach worked only for single Strings, not arrays). Thanks for any tips!

我知道这可能是一个非常基本的问题,但是关于在 web 上的 portlet 中传递数据的教程并不多(当我找到任何教程时,该方法仅适用于单个字符串,而不适用于数组)。感谢您提供任何提示!

PS: I checked that my javascript function works correctly:

PS:我检查了我的 javascript 功能是否正常工作:

<script>
    displayMessages(["One", "Two", "Three"]);
</script>

采纳答案by Simon

You need to have a method that outputs a string of the array in javascript array format. The jsp code is run on the server side and then returns html and javascript code in text. Then that code is executed on the client side.

您需要有一个以 javascript 数组格式输出数组字符串的方法。jsp 代码在服务器端运行,然后以文本形式返回 html 和 javascript 代码。然后在客户端执行该代码。

<%!
public static String getArrayString(String[] items){
    String result = "[";
    for(int i = 0; i < items.length; i++) {
        result += "\"" + items[i] + "\"";
        if(i < items.length - 1) {
            result += ", ";
        }
    }
    result += "]";

    return result;
}
%>

Of course you can do this with a StringBuffer for better performance, but this shows you the idea.

当然,您可以使用 StringBuffer 执行此操作以获得更好的性能,但这向您展示了这个想法。

Then you do something like this

然后你做这样的事情

<script>
    displayItems(<% getArrayString(items) %>);
</script>