【问题标题】:Filter dynamic data using ajax in spring在spring中使用ajax过滤动态数据
【发布时间】:2015-10-07 05:28:52
【问题描述】:

我正在做一个项目,我需要在 jsp/客户端显示记录。为此,我使用了一个循环来显示如下所示的数据,这对我来说很好。

JSP 中的 JSTL 代码

<c:if test="${!empty students}">
    <c:forEach var="student" items="${students}">
        <c:if test="${student.type == 'event'}">
            <div class="student_card">
                <h3>Student Card</h3>
                <h4 class="stu_name" objType="${student.type}" objId="${student.obj.id}">${student.obj.name}</h4>
                <p class="stu-name">${student.obj.branch.name}</p>
                <div>
                    <div class="description">
                        <p>Description:</p>
                        <p class="description_text">${student.obj.description}</p>
                    </div>
                    <div class="fee_date">
                        <img src="${pageContext.servletContext.contextPath}/resources/images/clock.png" alt="clock" id="clock">
                        <p class="date_gray">${student.formatDate(student.obj.startTime)}&mdash;${student.formatDate(student.obj.endTime)}</p>
                    </div>
                    <div class="stu_status">
                        <p>
                        Status: <span class="stu_green">${student.obj.status}</span>
                        </p>
                        <c:if test="${student.obj.status eq 'In Progress'}">
                            <div class="btn_compl" remove_it="event_${student.obj.id}">
                                <a class="compl_btn_blue">Complete</a>
                            </div>
                        </c:if>
                    </div>
                </div>
            </div>
        </c:if>
    </c:forEach>
</c:if>

我有一个包含多个字段e.g: Name, Gender, Age, class, etc. 的表单当用户点击这些字段中的任何一个时,我需要相应地display/filter 数据。

例如: 用户点击性别单选按钮并从中选择男性选项。因此,我需要显示所有男学生记录我不想提交表单并再次加载整页以节省时间我使用Ajax 过滤数据。我的Ajax函数是这样的。

Ajax

var data = 'studentName='+studentName+'&gender='+gender+'&studentClass='+studentClass+'&grades='+grades;

$.ajax({
    url: '${pageContext.servletContext.contextPath}/student/filter',
    type: 'POST',
    data: data,
    async: true,
    success: function(response) {
        /* Removing earlier data */
        $('.stu_info').remove();
        /* To display data dynamically which is not working for me */
        <c:forEach var="student" items="${filter}">
            $('.main_content').append('<div class="stu_info"><p>${student.type}</p></div>');
        </c:forEach>
    }
});

控制器:

@RequestMapping(value = "/student/filter", method = RequestMethod.POST)
public @ResponseBody Map<String, ? extends Object> filterStudents(@ModelAttribute(value = "studentName") String studentName, @ModelAttribute(value = "gender") String gender, @ModelAttribute(value = "studentClass") String studentClass, @ModelAttribute(value = "grades") String grades, BindingResult result, WebRequest webRequest, ModelMap map, Principal principal) {

    -------------------
    Code to filter Data
    -------------------

    map.put("filter", studentFilter);
    return Collections.singletonMap("filter", studentFilter);
}

问题:

我的 Ajax 在这里成功运行,我可以将数据放入包含过滤学生数据的过滤器中。但我无法在 jsp 端显示任何信息。我的jsp代码如下。

<c:if test="${!empty students}">
    <c:forEach var="student" items="${filter}">
        <c:if test="${student.type == 'event'}">
            <div class="student_card">
                <h3>Student Card</h3>
                <h4 class="stu_name" objType="${student.type}" objId="${student.obj.id}">${student.obj.name}</h4>
                <p class="stu-name">${student.obj.branch.name}</p>
                <div>
                    <div class="description">
                        <p>Description:</p>
                        <p class="description_text">${student.obj.description}</p>
                    </div>
                    <div class="fee_date">
                        <img src="${pageContext.servletContext.contextPath}/resources/images/clock.png" alt="clock" id="clock">
                        <p class="date_gray">${student.formatDate(student.obj.startTime)}&mdash;${student.formatDate(student.obj.endTime)}</p>
                    </div>
                    <div class="stu_status">
                        <p>
                        Status: <span class="stu_green">${student.obj.status}</span>
                        </p>
                        <c:if test="${student.obj.status eq 'In Progress'}">
                            <div class="btn_compl" remove_it="event_${student.obj.id}">
                                <a class="compl_btn_blue">Complete</a>
                            </div>
                        </c:if>
                    </div>
                </div>
            </div>
        </c:if>
    </c:forEach>
</c:if>

我认为这不起作用,因为 JSTL 代码在向用户显示内容之前在服务器端编译,我还检查了这个链接:Using JSTL inside Javascript。哪个状态我们不能在 jQuery 中使用 jstl 标签。

数据响应:

{
    "filter":
    [
        {
            "id":"123",
            "name":"jon",
            "class":"5",
            "startTime":1442206800000,
            "endTime":1444453200000,
            "percentage":88,
            "editable":true,
            "obj":
            {
                "id":"402880ed5012503801501252e2df0002",
                "authorizationRequired":false,
                "owner":
                {
                    "id":"402880f24ffeaaba014ffef2bb520015",
                    "school":
                    {
                        "id":"402880f24ffeaaba014ffef31aaf0017",
                        "name":"some school",
                        "enabled":true,
                        "size":300,
                        "sector":null,
                        "phone":"1231231232",
                        "location":"US"
                    }
                }
            }
        }
    ]
}

问题:

那么,有什么方法可以在客户端显示新的/动态数据。

任何建议或链接都​​会有所帮助。

【问题讨论】:

    标签: java jquery ajax spring jsp


    【解决方案1】:

    您的 ajax 调用有问题。您正在 jquery 代码中编写 jstl 代码。 Jquery 在客户端运行,而 jstl 代码在服务器端运行。

    var data = 'studentName='+studentName+'&gender='+gender+'&studentClass='+studentClass+'&grades='+grades;
    
    $.ajax({
        url: '${pageContext.servletContext.contextPath}/student/filter',
        type: 'POST',
        data: data,
        async: true,
        success: function(response) {
    
            alert( "Response: " + response ); // <--------add this
    
            /* Removing earlier data */
            $('.stu_info').remove();
    
            // remove below code and write pure jquery code to iterate response as a json.
    
            /* To display data dynamically which is not working for me */
            <c:forEach var="student" items="${filter}">
                $('.main_content').append('<div class="stu_info"><p>${student.type}</p></div>');
            </c:forEach>
        }
    });
    

    参考:jQuery loop over JSON result from AJAX Success?


    更新:如前所述。

    1. 将返回类型更改为 List。
    2. 您可以在 ajax 响应中迭代列表,如下所示

      jQuery.each(response, function(index, item) {
          //now you can access properties using dot notation
          alert(item.id);
          alert(item.name);
          alert(item.obj.id);
          alert(item.obj.owner.school.phone);
      });
      

    【讨论】:

    • 是的,这就是我面临的问题。我知道这行不通我想知道是否有其他方法可以在不刷新页面的情况下动态显示数据..
    • 我在答案中添加了一个链接。参考那个链接。
    • 所以这意味着我需要发送数据作为响应,然后我需要使用链接中描述的每个函数。我说的对吗?
    • 在您的 jquery 函数中添加上述警报并发布返回的 JSON。
    • 这取决于返回的 json 的结构。如果它不包含列表或地图,那么您将不需要每个函数。
    【解决方案2】:

    JSTL 在服务器上呈现。如果您必须在客户端上呈现响应,它将无济于事。使用 Javascript,特别是 jQuery。

    假设studentFilter 是某种集合,你应该直接返回它:

    @ResponseBody List<Student> filterStudent(...) {
    }
    

    现在,Spring 将返回 Java 数据类型的 JSON 表示,如下所示:

    [
        {
            "type": "Some Value"
        },
        {
            "type": "Another Value"
        }
    ]
    

    现在,在 Javascript 中:

    $.each(response, function(index, student) {
        $('.main_content').append('<div class="stu_info"><p>' + student.type + '</p></div>');    
    });
    

    【讨论】:

    • 我更新了我的问题中的 JSON。您能否检查一下并告诉我是否可以使用您的解决方案,因为我的 JSON 中有多个级别对象。
    • 多层没问题,只是嵌套对象而已。您可以在 Javascript 中遍历它们,就好像它们是 Java 中的嵌套对象一样。
    • 谢谢!为您的回答 +1
    猜你喜欢
    • 1970-01-01
    • 2023-03-10
    • 2021-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-29
    • 2019-06-12
    • 1970-01-01
    相关资源
    最近更新 更多