ajax+servlet
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <style> .a{ margin-top: 20px; } .b{ font-size: 20px; width: 160px; color: white; background-color: greenyellow; } .tb, td { border: 1px solid black; font-size: 22px; } </style> </head> <body> <script type="text/javascript" src="js/jquery-3.3.1.js"></script> <div align="center"> <h1 style="color: red;">学生信息列表</h1> <table class="tb" id="tb"> <tr> <td>id</td> <td>学生名称</td> <td>班级</td> <td>性别</td> <td align="center" colspan="2">操作</td> </tr> </table> </div> <script type="text/javascript"> $(function() { $.ajax({ type:'POST', url:'Servlet?method=list', success:function(data){ if(data.length>0){ var tr=''; $.each(data,function(index){ tr+='<tr><td>'+data[index].id+'</td><td>'+data[index].name+'</td><td>'+data[index].classroom+'</td>'+ '<td>'+data[index].sex+'</td><td><a href="Servlet?method=getStudentById&id='+data[index].id+'">修改</a> <a href="Servlet?method=del&id='+data[index].id+'">删除</a></td></tr>' }) $('#tb').append(tr) } }, error:function(){ alert("错误") } }); }); </script> </body> </html>
private void list(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { req.setCharacterEncoding("utf-8"); List<Student> list = dao.search(); JSONArray array = new JSONArray(); if(list.size()>0) { for (int i = 0; i < list.size(); i++) { JSONObject object = new JSONObject(); object.put("name", list.get(i).getName()); object.put("id", list.get(i).getId()); object.put("classroom", list.get(i).getClassroom()); object.put("sex", list.get(i).getSex()); array.add(object); } System.out.println(array); resp.setContentType("application/json"); resp.setCharacterEncoding("utf-8"); resp.getWriter().write(array.toString()); } }
可以在界面上局部刷新,无需点击list.jsp链接才能看到列表