从 JSTL 代码在 javascript 中设置数组值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13190306/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Set array values in javascript from JSTL code
提问by Marcus Dryice Koh
I have a code that looks like this:
In AnalyzeUserClient.jsp:
我有一个如下所示的代码:
在 AnalyzeUserClient.jsp 中:
<c:set var="arrayList"><%= (ArrayList<String>)request.getSession().getAttribute("arrayList") %></c:set>
var sessionId = [];
<c:forEach items=${arrayList} var="id">
sessionId.push("${id}"); // add them one at a time, assuming string values
</c:forEach>
However,this line:
但是,这一行:
sessionId.push("${id}");
does not seem to be passing the values into the array "sessionId" (I viewed the source code on browser).So the question is,what can I do to pass the values into the array?
EDIT:I just realised that there are some problems as JSTL is server-side and JavaScript is client-side.So is there a workaround on it?
似乎没有将值传递到数组“sessionId”中(我在浏览器上查看了源代码)。所以问题是,我该怎么做才能将值传递到数组中?
编辑:我刚刚意识到存在一些问题,因为 JSTL 是服务器端而 JavaScript 是客户端。所以有解决方法吗?
回答by JB Nizet
Don't mix EL and scriptlets. In fact, forget about scriptlets completely:
不要混合使用 EL 和 scriptlet。事实上,完全忘记 scriptlet:
var sessionId = [];
<c:forEach items="${sessionScope.arrayList}" var="id">
sessionId.push("${id}");
</c:forEach>
Note though that this will generate invalid JavaScript if one of the IDs happens to contain a double quote. So you'd better JavaScript-escape the IDs before, in your controller. And I would suggest a completely different approach: serialize the list of IDs to a JSON string in your controller, and store this JSON string in request attribute. The JSP page will just need
但请注意,如果 ID 之一恰好包含双引号,这将生成无效的 JavaScript。所以你最好在你的控制器中对 ID 进行 JavaScript 转义。我建议采用完全不同的方法:将 ID 列表序列化为控制器中的 JSON 字符串,并将此 JSON 字符串存储在请求属性中。JSP 页面只需要
var sessionId = ${jsonEncodedSessionIds};
which will translate to the following generated code:
这将转换为以下生成的代码:
var sessionId = ["id1", "id2"];