七、在Jquery中使用Ajax
在 JQuery 中提供了对 Ajax 的封装,让我们在使用 Ajax 技术时变得更加容易。在 JQuery 中提供了很多的基于 Ajax 发送异步请求的方法,如:$.ajax()、$.get()、$.post()、$.getJSON()。
7.1 $.ajax()在异步请求中提交数据
在$.ajax()方法中通过 data 属性来存放提交的数据,支持 JSON 格式的数据
7.1.1 提交普通格式数据
在 data 属性中我们可以通过两种方式来指定需要提交的数据。一种是通过 name=value&name=value 的结构。另一种是通过 JavaScript 对象来指定提交数据。无论使用哪种方式在Servlet中都是通过request.getParameter方法根据name获取value的。
通过 JavaScript 对象指定提交数据
data:{ userid:100, username:"zhangsan" }
7.1.2 提交 JSON 格式数据
在$.ajax()中提交 JSON 格式的数据需要使用 post 方式提交,通过 JSON.stringify()函数将 JavaScript 对象转换成 JSON 格式的字符串。在 Servlet 中通过字符输入获取提交的 JSON 格式的数据。
data:JSON.stringify({name:value,name:value......})
在 Servlet 中通过 req.getReader().readLine()来获取提交的数据。
7.2 $.ajax()处理响应中的 JSON 格式数据
$.ajax()方法会根据 dataType 属性中的值自动对响应的数据做类型处理。如果响应的是 一个 JSON 格式的数据,那么 dataType 的值为“JSON”,在回调函数中我们得到的直接就是 JSON 字符串转换完的 JavaScript 对象。不需要在使用 JSON.parse()做格式的转换处理。
八、Ajax实现增删改查
8.1 创建JavaBean User类
package com.ajax.pojo; public class User { private Integer id; private String username; private String password; private Double salary; private String birthday; public User() { } public User(Integer id, String username, String password, Double salary, String birthday) { this.id = id; this.username = username; this.password = password; this.salary = salary; this.birthday = birthday; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Double getSalary() { return salary; } public void setSalary(Double salary) { this.salary = salary; } public String getBirthday() { return birthday; } public void setBirthday(String birthday) { this.birthday = birthday; } @Override public String toString() { return "User{" + "id=" + id + ", username='" + username + '\'' + ", password='" + password + '\'' + ", salary=" + salary + ", birthday='" + birthday + '\'' + '}'; } }
8.2 创建index.jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>$Title$</title> <script type="text/javascript" src="js/jquery-3.6.0.js"></script> </head> <body> <div> <table align="center" width="60%" border="1"> <tr> <td>ID:</td> <td><input type="text" name="id" id="id"/></td> <td>姓名:</td> <td><input type="text" name="username" id="username"/></td> <td>密码:</td> <td><input type="text" name="password" id="password"/></td> </tr> <tr> <td>收入:</td> <td><input type="text" name="salary" id="salary"/></td> <td>出生日期:</td> <td><input type="text" name="birthday" id="birthday"/></td> <td colspan="2"></td> </tr> <tr align="center"> <td colspan="6"> <input type="button" value="添加用户" id="add" /> <input type="button" value="更新用户" id="update"/> </td> </tr> </table> <hr/> <table align="center" width="60%" bgcolor="" border="1" id="myTable"> <thead> <tr align="center"> <td>ID</td> <td>姓名</td> <td>密码</td> <td>收入</td> <td>生日</td> <td>操作</td> </tr> </thead> <tbody id="tBody"></tbody> </table> </div> </body> <script> /*页面启动自动执行该区域的代码*/ $(function () { //初始化用户数据 getData(); }); /* 初始化用户数据*/ function getData() { //发送ajax请求,getJSON表示返回的是JSON格式的数据。 $.getJSON("user.do",{flag:"getData"},function (result) { //获取到数据后在页面中展示数据 showUsers(result); }) } /*展示用户数据*/ function showUsers(result) { //将数据拼接成HTML var str = ""; $.each(result,function () { str+="<tr align='center'>"+ "<td id='"+this.id+"'>"+this.id+"</td>"+ "<td id='"+this.username+"'>"+this.username+"</td>"+ "<td id='"+this.password+"'>"+this.password+"</td>"+ "<td id='"+this.salary+"'>"+this.salary+"</td>"+ "<td id='"+this.birthday+"'>"+this.birthday+"</td>"+ "<td><a href='#' onclick='preUpdate("+this.id+")'>更新</a> <a href='#' onclick='del("+this.id+")'>删除</a></td>"+ "</tr>" }) $("#tBody").prepend(str); } /*添加用户*/ $("#add").click(function(){ updateUser("add"); }); /*修改用户*/ $("#update").click(function () { updateUser("update"); }); /*删除*/ function del(id) { $.get("user.do",{id:id},function (result) { alert(result); location.reload(); }) } /*选择要更新的数据带到表单中*/ function preUpdate(id) { console.log(id); var arr = new Array(); //遍历选中行中的用户数据 $("#"+id).closest("tr").children().each(function (index,element) { if (index<=4){ arr[index] = element.innerText; } }); //获取表单数据 $("#id").val(arr[0]); $("#id").attr("readonly",true);//id不可编辑 $("#username").val(arr[1]); $("#password").val(arr[2]); $("#salary").val(arr[3]); $("#birthday").val(arr[4]); } function updateUser(flag) { var id = $("#id").val(); var username = $("#username").val(); var password = $("#password").val(); var salary = $("#salary").val(); var birthday = $("#birthday").val(); var data = { id:id, username:username, password:password, salary:salary, birthday:birthday, flag:flag, }; $.get("user.do",data,function (result) { alert(result); location.reload(); }) } </script> </html>
8.3 创建userservlet
package com.ajax.servlet; import com.ajax.pojo.User; import com.alibaba.fastjson.JSON; import javax.servlet.ServletContext; 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; import java.util.ArrayList; import java.util.Comparator; @WebServlet("/user.do") public class UserServlet extends HttpServlet { /*初始化用户数据*/ @Override public void init() throws ServletException { ArrayList<User> usersList = new ArrayList<>(); User zs = new User(1, "zhangsan", "123", 2000d, "2001-12-04"); User ls = new User(2, "lisi", "12344", 3000d, "2001-12-07"); User ww = new User(3, "wangwu", "123423", 2040d, "2001-12-04"); User zl = new User(4, "zhaoliu", "123423", 2600d, "2001-12-05"); User tq = new User(5, "tianqi", "124453", 2070d, "2001-12-04"); usersList.add(zs); usersList.add(ls); usersList.add(ww); usersList.add(zl); usersList.add(tq); this.getServletContext().setAttribute("userList", usersList); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //获取请求的参数 String flag = req.getParameter("flag"); if ("getData".equals(flag)){ getData(req, resp); }else if ("add".equals(flag)){ //添加 addUser(req, resp); }else if ("update".equals(flag)){ //更新 update(req, resp); }else { //删除 delete(req, resp); } } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } //获取用户数据 public void getData(HttpServletRequest request,HttpServletResponse response) throws IOException { ArrayList<User> userList = (ArrayList<User>) this.getServletContext().getAttribute("userList"); //将数据转换为JSON字符串输出到页面上 String s = JSON.toJSONString(userList); response.setContentType("application/json"); //输出流 PrintWriter writer = response.getWriter(); writer.println(s); writer.flush(); writer.close(); } //添加 public void addUser(HttpServletRequest request, HttpServletResponse response) throws IOException { User user = this.createUser(request, response); ServletContext servletContext = this.getServletContext(); ArrayList<User> userList = (ArrayList<User>) servletContext.getAttribute("userList"); userList.add(user); response.setContentType("text/plain;charset=utf-8"); PrintWriter writer = response.getWriter(); writer.println("添加成功"); writer.flush(); writer.close(); } public User createUser(HttpServletRequest request, HttpServletResponse response){ String id = request.getParameter("id"); String username = request.getParameter("username"); String password = request.getParameter("password"); String salary = request.getParameter("salary"); String birthday = request.getParameter("birthday"); User user = new User(); user.setId(Integer.parseInt(id)); user.setUsername(username); user.setPassword(password); user.setSalary(Double.parseDouble(salary)); user.setBirthday(birthday); return user; } //更新用户 public void update(HttpServletRequest request, HttpServletResponse response) throws IOException { User user = this.createUser(request, response); //更新后的user对象 ServletContext servletContext = this.getServletContext(); ArrayList<User> userList = (ArrayList<User>) servletContext.getAttribute("userList"); for (User user1 : userList) { if (user1.getId() == user.getId()) { userList.remove(user1); break; } } //添加新的user到集合 userList.add(user); //按照id重新排序 userList.sort(new Comparator<User>() { @Override public int compare(User o1, User o2) { return o1.getId() - o2.getId(); } }); //输出到页面 response.setContentType("text/plain;charset=utf-8"); PrintWriter writer = response.getWriter(); writer.println("更新成功"); writer.flush(); writer.close(); } //删除 public void delete(HttpServletRequest request, HttpServletResponse response) throws IOException { String id = request.getParameter("id"); ServletContext servletContext = this.getServletContext(); ArrayList<User> userList = (ArrayList<User>) servletContext.getAttribute("userList"); for (User user : userList) { if (user.getId() == Integer.parseInt(id)){ userList.remove(user); break; } } response.setContentType("text/plain;charset=utf-8"); PrintWriter writer = response.getWriter(); writer.println("删除成功"); writer.flush(); writer.close(); } }