Passing array from .jsp to javascript function

后端 未结 1 1188
清歌不尽
清歌不尽 2020-12-11 09:41

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:

相关标签:
1条回答
  • 2020-12-11 10:05

    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>
    
    0 讨论(0)
提交回复
热议问题