将数组从.jsp传递给javascript函数 [英] Passing array from .jsp to javascript function
问题描述
我有一个Liferay portlet,我从action阶段传递一个String数组以在我的.jsp文件中呈现阶段。我可以访问数组并像下面这样遍历它:
< c:forEach var =itemitems = $ {arrayItems} >
< p> $ {item}< / p>
< / c:forEach>
这只是为了检查传递数据是否正常工作...但是,我想通过这整个数组到我的JavaScript函数(处理渲染数据到画布)。任何想法如何做到这一点?
到目前为止,我已经尝试了以下内容:
<%
String [] items;
items = new String [((String [])request.getAttribute(arrayItems))。length];
items =((String [])request.getAttribute(arrayItems));
%>
< script>
displayItems(<%arrayItems%>);
< / script>
还有
<脚本>
displayItems($ {arrayItems});
< / script>
我知道这可能是非常基本的问题,但没有太多关于在portlet中传递数据的教程在网上(当我发现任何,这种方法只适用于单个字符串,而不是数组)。感谢您的任何提示!
PS:我检查了我的javascript功能正常工作:
<脚本>
displayMessages([One,Two,Three]);
< / script>
您需要一种方法输出字符串以javascript数组格式显示数组。
jsp代码在服务器端运行,然后在文本中返回html和javascript代码。然后,该代码在客户端执行。
<%!
public static String getArrayString(String [] items){
String result =[;
for(int i = 0; i< item.length; i ++){
result + =\+ items [i] +\;
if(i< items.length - 1){
result + =,;
}
}
result + =];
返回结果;
}
%>
当然,您可以使用StringBuffer来获得更好的性能,但这会向您显示这个想法。 / p>
然后你做这样的事情
< script>
displayItems(<%getArrayString(items)%>);
< / script>
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:
<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?
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!
PS: I checked that my javascript function works correctly:
<script>
displayMessages(["One", "Two", "Three"]);
</script>
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.
<%!
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.
Then you do something like this
<script>
displayItems(<% getArrayString(items) %>);
</script>
这篇关于将数组从.jsp传递给javascript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!