使用EL将Java集分配给Javascript数组 [英] Assigning a Java Set to a Javascript array using EL

查看:83
本文介绍了使用EL将Java集分配给Javascript数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我尝试使用Spring和JSP EL将Set传递到.jsp页面,然后将Set的成员分配给Javascript数组,以供以后在客户端脚本中使用.

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.

例如,如果我有Java集 exampleSet:{"A","B","C"}

For example, if I have the Java Set exampleSet: { "A", "B", "C"}

我将其作为spring ModelandView对象的一部分传递给客户端.

I pass it to the client side as part of a spring ModelandView object.

在客户端JSP中,我可以使用EL将集合输出为 $ {model.exampleSet} ,由JSP解析为[A,B,C].

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.

我想要做的是将exampleSet的内容分配给一个javascript字符串数组,这样您将得到

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"]

我找不到执行此操作的直接方法.另一个明显的方法是遍历Set,但是由于我无法在javascript中计算Set的大小,因此我也不认为可以做到这一点.

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.

推荐答案

JavaScript在浏览器上执行. JSP在服务器上呈现.您在这里错过了执行环境的生命周期.

JavaScript executes on the browser. The JSP is rendered on the server. You're missing the lifetimes of the execution environments here.

您要做的是

<script>
var exampleSet = [
  <c:forEach var="item" items="${theSetVariable}" varStatus="loop">
    "${item}"
    <c:if test="${!loop.last}">,</c:if>
  </c:forEach>
]
<script>

因此,您要遍历JSP中的Set,以创建HTML/JavaScript,该HTML/JavaScript会创建代码以表示在浏览器上呈现的Javascript数组.

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.

这篇关于使用EL将Java集分配给Javascript数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆