Assigning a Java Set to a Javascript array using EL

大兔子大兔子 提交于 2020-01-05 07:12:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!