json数据通过后台渲染到jsp页面上

效果如下

代码实现:

StudentInfoServlet

package com.hp.controller;



import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


@WebServlet(name = "StudentInfoServlet",urlPatterns = "/StudentInfoServlet")
public class StudentInfoServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       /* super.service(req, resp); */
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        resp.setCharacterEncoding("UTF-8");

        String s1 = "{\n"+
       "\"rows\":[{\"name\":\"张三\",\"age\":\"15\",\"class\":\"15网络\"},{\"name\":\"李四\",\"age\":\"22\",\"class\":\"17软件\"},{\"name\":\"王五\",\"age\":\"33\",\"class\":\"16信息\"},{\"name\":\"叫兽\",\"age\":\"21\",\"class\":\"15网络\"}]}";

        //2.开始输出
        PrintWriter writer= resp.getWriter();
        writer.println(s1);
        writer.close();
       
    }
}

jsp

<%--
  Created by IntelliJ IDEA.
  User: 86151
  Date: 2021/8/2
  Time: 19:46
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>
<head>
    <title>Title</title>
    <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
    <style>
        table{
            width:600px;
            height: 120px;
            border-collapse: collapse;
        }
        td{
        border: 1px solid aqua;
            text-align: center;

    }
    </style>
</head>
<body>
<table style="border: 1px solid aquamarine" align="center">
    <thead>
    <tr>
        <th align="center" style="background: aquamarine" colspan="4" height="40px">表格</th>
    </tr>
    <tr>
        <td><input type="checkbox" name="fuxuan"></td>
        <td>姓名</td>
        <td>年龄</td>
        <td>班级</td>
    </tr>
    </thead>
    <tbody id="content">

    </tbody>
</table>
<script>
    $(function () {
        $.ajax({
            url: "/StudentInfoServlet",
            type: 'GET',
            data: '',
            dataType: 'JSON',
            success: function (res) {
               $.each(res.rows,function (index,item) {
                  $("#content").append("<tr>"+"<td><input type='checkbox' name='fuxuan'></td>"+"<td>"+item.name+"</td>"+"<td>"+item.age+"</td>"+"<td>"+item.class+"</td>"+"</tr>")
               })
             //  console.log(res)
            }
        });
    });
</script>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值