问题描述
我有一个看起来像这样的代码:
在AnalyzeUserClient.jsp中:
I have a code that looks like this:
In 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>
但是,这一行:
sessionId.push("${id}");
似乎没有将值传递到数组"sessionId"中(我在浏览器上查看了源代码).所以问题是,我应该怎么做才能将值传递到数组中?
我刚刚意识到存在一些问题,因为JSTL是服务器端的,而JavaScript是客户端的.所以有没有解决的办法?
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?
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?
推荐答案
请勿混合使用EL和脚本.实际上,完全不用考虑scriptlet:
Don't mix EL and scriptlets. In fact, forget about scriptlets completely:
var sessionId = [];
<c:forEach items="${sessionScope.arrayList}" var="id">
sessionId.push("${id}");
</c:forEach>
请注意,如果其中一个ID恰好包含双引号,则会生成无效的JavaScript.因此,最好先在控制器中使用JavaScript转义ID.我建议一种完全不同的方法:在控制器中将ID列表序列化为JSON字符串,然后将此JSON字符串存储在request属性中. JSP页面将只需要
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
var sessionId = ${jsonEncodedSessionIds};
它将转换为以下生成的代码:
which will translate to the following generated code:
var sessionId = ["id1", "id2"];
这篇关于通过JSTL代码在JavaScript中设置数组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!