我正在我的主 JSP 页面中使用 Ajax 请求获取一些数据。
main.jsp
的片段function gu(){
$.get('/admin/getAllUsers', {}, function(data) {
console.log(data); // see below
$("#allUsersData").html(data);
});
}
在我的 Spring Controller 中,我将所有用户添加到不同的 JSP 页面。
MainController.java
的片段@RequestMapping(value = "/admin/getAllUsers", method = RequestMethod.GET)
public String getAllUsers(Model model){
List<User> users = userRepository.findAll();
System.out.println(users.size()); // output: 3
model.addAttribute("allUsers", users);
return "data/all-users";
}
现在在 all-users.jsp 我有一个 <c:forEach>
这应该将所有用户加载到 html 表中:
<table class="table">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<c:if test="${not empty allUsers}">
<c:forEach items="${allUsers}" var="usr">
<tr>
<td>${usr.firstName}</td>
<td>${usr.lastName}</td>
<td>${usr.username}</td>
<td>${usr.creationDate}</td>
</tr>
</c:forEach>
</c:if>
</tbody>
</table>
但是,当我将来自请求的 html 添加到我的主 JSP 页面时,会显示一个空表。当我记录 Ajax 请求的结果时,我发现用户数据被插入到 all-users.jsp 中:
<c:if test="true">
<c:forEach items="[User{id=1, username='username1', firstName='John', lastName='Doe', roles=[Role{id=1, name='ROLE_USER'}], creationDate=2018-02-19T08:58:13.333}, User{id=2, username='username2', firstName='John2', lastName='Doe2', roles=[Role{id=3, name='ROLE_USER'}], creationDate=2018-02-19T08:58:13.471}]" var="usr">
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</c:forEach>
</c:if>
为什么会发生数据加载到数据 JSP 页面,但在附加到主 JSP 页面时没有显示?
最佳答案
您能检查一下吗,也许您没有在 JSP 文件中包含核心标记库。 您将通过在文件顶部插入以下行来执行此操作。
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
关于ajax - 为什么 <c :forEach> not working with Ajax request in JSP Spring?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48870762/