ajax - 为什么 <c :forEach> not working with Ajax request in JSP Spring?

标签 ajax spring jsp controller

我正在我的主 JSP 页面中使用 Ajax 请求获取一些数据。

ma​​in.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/

相关文章:

java - 由于在 @Transactional 方法中使用带有 Hibernate、Spring 和 CrudRepository 接口(interface)的 JPA 关闭 session 导致延迟加载异常

Spring Boot Actuator无法显示磁盘空间信息

java - Struts 2 - 填充 s :select from server based on first s:select

java - 动态Web元素不读取CSS

JavaScript EJB变量字段保存值?

javascript - Ajax DropDown 根据之前的下拉菜单填充

spring - 如何在 Spring Autowiring 之前让 DBUnit @DatabaseSetup 发生?

java - c :forEach issue when part of javascript function

javascript - 当我使用经典的 asp、jquery 和 ajax 从第一个下拉列表中选择一个值时,如何显示所选项目的表格?

javascript - AJAX 将类添加到表格单元格