问题
So, I am trying to pass a Set into a .jsp page using Spring and JSP EL, and then assign the members of the set to a Javascript array to use later in client-side scripts.
For example, if I have the Java Set exampleSet: { "A", "B", "C"}
I pass it to the client side as part of a spring ModelandView object.
In the client-side JSP, I can use EL to output the set as ${model.exampleSet} , which gets parsed into [A, B, C] by JSP.
What I want to do is assign the contents of exampleSet to an array of javascript strings, so you get something like
var exampleSet = ["A", "B", "C"]
I can't find a direct way to do this. The other obvious approach to this is to loop through the Set, but as I can't work out the size of the Set in javascript, I don't think I can do this either.
回答1:
JavaScript executes on the browser. The JSP is rendered on the server. You're missing the lifetimes of the execution environments here.
What you would do is
<script>
var exampleSet = [
<c:forEach var="item" items="${theSetVariable}" varStatus="loop">
"${item}"
<c:if test="${!loop.last}">,</c:if>
</c:forEach>
]
<script>
So, you're looping through the Set in the JSP, to create the HTML/JavaScript, that creates code to represent the Javascript array when rendered on the browser.
来源:https://stackoverflow.com/questions/12076654/assigning-a-java-set-to-a-javascript-array-using-el