3

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>

1 Answer 1

3

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

3 Comments

i have used above but taken as param the Writer object. Another way is to use JSON but that is more re work though better in the long run
When declaring a function in a jsp page one needs to use <%! and %>. I updated the answer with this change. However if you're going to create javascript arrays in different pages you might want to create a regular .java file that you then include like this <%@ page import="com.mycompany.MyUtilClass" %>
When I call displayItems(<% getArrayString(messageContents); %>);, I get the following: ERROR [MinifierUtil:108] 4: 20: illegally formed XML syntax...

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.