Asynchronous loading data using ajax

Asynchronous loading data using ajax

  1. controller assigned to User

    @RequestMapping("/a2")
    public List<User> a2() {
        List<User> userlist = new ArrayList<User>();
        userlist.add(new User("大头儿子", 6, "男"));
        userlist.add(new User("小头爸爸", 30, "男"));
        userlist.add(new User("老王", 45, "男"));
        return userlist;
    }
  2. button和table

    <input type="button" id="btn" value="加载数据">
    <table>
        <thead>
        <tr>
            <td>姓名</td>
            <td>年龄</td>
            <td>性别</td>
        </tr>
        </thead>
        <tbody id="content">
        </tbody>
    </table>
  3. jQuery Import and function

    <script src="${pageContext.request.contextPath}/statics/js/jquery-3.4.1.js"></script>
    <script>
        $(function () {
            $("#btn").click(function () {
                $.post("${pageContext.request.contextPath}/a2", function (data) {
                    //console.log(data);
                    var html = "<>";
    
                    for (let i = 0; i < data.length; i++) {
                        html += "<tr>" +
                            "<td>" + data[i].name + "</td>" +
                            "<td>" + data[i].age + "</td>" +
                            "<td>" + data[i].sex + "</td>" +
                            "</tr>"
                    }
                    $("#content").html(html);
                })
            })
        })
    </script>
  4. Results page

Guess you like

Origin www.cnblogs.com/pinked/p/12233403.html