Convert arrayList to javascript array
Asked Answered
S

1

0

I am sending an arrayList from a java file to a .jsp file

In order to receive that array I used the following code

var words = 
        [
            <c:forEach begin="0" items="${requestScope.WordList}" var = "word">
                word,
             </c:forEach>
        ];

however it is not working .. any Idea of how to do it ?

Seaware answered 21/4, 2013 at 16:12 Comment(4)
I don't see a question mark anywhere !Parquet
it is not working is too generalized, please be more specific!Parquet
I don't think it is good practice to build JSON arrays this way. Just use a 3rd party library to do that. This kind of approach can create a lot of problems.Accrescent
possible duplicate of Converting a Java ArrayList of strings to a JavaScript arrayBackler
P
1

Possible fix (Bad fix):

var words = 
    [
        <c:forEach items="${requestScope.WordList}" var="word" 
         varStatus="status">
          "${word}"<c:if test="${not status.last}">,</c:if>
        </c:forEach>
    ];

OR

Convert the Java ArrayList to JSON String, and use JSON.parse() to get Javascript object.

Parquet answered 21/4, 2013 at 16:18 Comment(4)
As the type of word probably is string you will have to put quotes around ${word}. I.e. put "${word}", in the c:forEach. A secound problem would be, that you will have a comma at the end of the array definition.Scleroderma
no not working for the last line it gave the error expected ; but found ]Seaware
Comma at the end is fine with most browsersBortz
Don't forget to escape the word stringBortz

© 2022 - 2024 — McMap. All rights reserved.