前端解析Json数据并展示

前端代码:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script src="${pageContext.request.contextPath}/static/js/jquery-3.6.0.js"></script>
    <script>
        $(function () {
            $("#btn").click(function () {
                $.post("${pageContext.request.contextPath}/a2",
                function (data) {
                    var html="";
                    for(let i=0;i<data.length;i++)//let比var更安全
                    {
                        html+="<tr>"+
                            "<td>"+data[i].name+"</td>"+
                            "<td>"+data[i].age+"</td>"+
                            "<td>"+data[i].sex+"</td>"+
                            "</tr>"
                    }
                    $("#content").html(html);
                });
            })
        })
    </script>
</head>
<body>
<input type="button" id="btn" value="加载数据">
<table>
    <tr>
        <td>姓名</td>
        <td>年龄</td>
        <td>性别</td>
        <tbody id="content">
        </tbody>
    </tr>
</table>
</body>
</html>

        给btn按钮绑定点击事件,让其执行异步请求, $.post有四个参数url(请求路径),data(请求的数据),success(当请求成功时的回调函数),eorr(请求失败时的回调函数).

        在<tbody>标签中拼接html代码,回调函数填充数据.

后端代码:

package com.rk.controller;
import com.rk.pojo.User;
import com.sun.deploy.net.HttpResponse;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController//加上这个不会返回到视图解析器
public class AjaxController {

@RequestMapping("/a2")
    public List<User> a2(){
        ArrayList<User> list = new ArrayList<User>();
        list.add(new User("罗林",1,"男"));
        list.add(new User("王敏",2,"女"));
        list.add(new User("杜佳伟",3,"男"));
        return list;
    }
}

Guess you like

Origin blog.csdn.net/m0_46979453/article/details/120612594