前端解析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;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Rk..

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值