ajax jquery实现分页

模仿以上代码


html js部分

<body onload="loadData()">
<h2>评论区</h2>
<table id="mytable">
    <tr>
        <th>name</th>
        <th>评论</th>
        <th>score</th>
    </tr>

</table>
<button onclick="reducePage()">上一页</button>
<button onclick="addPage()">下一页</button>
//跳转到指定页面,可以获取输入框的值
<script>
    var currentPage = 1;
    var gid = ${goods.id};
    function addPage() {
        currentPage = currentPage + 1;
        loadData();
    }

    function reducePage() {
        currentPage = currentPage - 1;
        loadData();
    }

    function loadData() {

        // $(".detail").remove();//每次从api获取值时,先清除表格tr的内容
        $.ajax({
            url:"GetCommentsController",
            method:"get",
            data:"currentPage="+currentPage+"&gid="+gid,
            success:function (result) {
                $(".detail").remove();//每次从api获取值时,先清除表格tr的内容
                var results = JSON.parse(result);
                for(var i=0;i<results.length;i++){
                    var id = results[i].id;
                    var content = results[i].content;
                    var user = results[i].user.name;
                    var score = results[i].score;
                    appendData(content,user,score);
                }
            }
        });
    }
    function appendData(content,user,score) {
        var text = '<tr class="detail"><td>'+user+'</td><td>'+content+'</td><td>'+score+'</td></tr>';
        console.log(text);
        $('#mytable').append(text);
    }

servlet部分

@WebServlet(name = "GetCommentsController",urlPatterns = {"/GetCommentsController"})
public class GetCommentsController extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String gid = request.getParameter("gid");
        String currentPage = request.getParameter("currentPage");
        System.out.println(gid+" "+currentPage);
        CommentService cs = new CommentServiceImpl();
        Goods goods = new Goods();
        goods.setId(Integer.parseInt(gid));
        Page page = new Page();
        page.setNum(3);
        page.setCurrentPage(Integer.parseInt(currentPage));
        page.setTotal(PageUtil.totalByGoods(Integer.parseInt(gid),3));
        List<Comment> commentList= cs.getAllComments(goods,page);
        Gson gson = new Gson();
        String str = gson.toJson(commentList);
        System.out.println(str);
        response.getWriter().write(str);


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_32296307/article/details/80385419