0

我已将数组 userName[][] 从 servlet 转发到 JSP。我可以访问数组元素${userName[2][3]},但我不能使用变量遍历数组。例如${userName[i][j]}${userName[<%=i>][<%=j>]}不工作。

另外,我应该将我的索引变量声明为 var(JS),因为我的代码也使用 JS 从数组中绘制图形,还是需要使用 JSTL?我是 JSP 的新手

4

1 回答 1

1

以下是您在 JSTL 中遍历数组的方法(请注意,我将您的 userName 变量复数,因为它是一个数组):

<c:forEach var="userName" items="userNames">
    // do something with the userName
</c:forEach>

由于您的数组是数组数组,因此您可以嵌套两次迭代:

<c:forEach var="innerArray" items="userNames">
    <c:forEach var="element" items="innerArray">
         // do something with the element
    </c:forEach>
</c:forEach>

请注意,JavaScript 在客户端执行,而 JSP 在服务器端执行。当 JS 代码执行时,它无权访问您的服务器端 Java 数组。如果您需要在客户端访问 Java 数组的内容,您应该使用 JSON 对其进行序列化,并在 JavaScript 中解析生成的 JSON 字符串。

于 2012-04-11T07:10:28.753 回答