AJAX基本&&JSON基础

快来打我* 2024-03-27 12:59 157阅读 0赞

目录

一、AJAX概述

二、AJAX快速入门

三、案例——使用AJAX验证用户名是否存在

四、Axios框架

五、JSON

5.1 JSON概述

5.2 JSON基础语法

5.3 JSON数据和Java对象转换

5.4 案例——查询所有(AJAX、JSON)

5.5 案例——新增品牌


一、AJAX概述

928dcc3a62e34ed1a04a5ba5088ac2ca.png

68fd9123001b4567b2d746bf0187eb8e.png

5035dfec83834f1c80ee77b501dd3424.png

885595fd87dc4e6ea57d3e32603070f0.png

二、AJAX快速入门

00ff14b32b3e4b1ebd4fc3e5742178ac.png

  1. <script>
  2. //1. 创建核心对象
  3. var xhttp;
  4. if (window.XMLHttpRequest) {
  5. xhttp = new XMLHttpRequest();
  6. } else {
  7. // code for IE6, IE5
  8. xhttp = new ActiveXObject("Microsoft.XMLHTTP");
  9. }
  10. //2. 发送请求
  11. xhttp.open("GET", "http://localhost:8080/ajax-demo/ajaxServlet");
  12. xhttp.send();
  13. //3. 获取响应
  14. xhttp.onreadystatechange = function() {
  15. if (this.readyState == 4 && this.status == 200) {
  16. alert(this.responseText);
  17. }
  18. };
  19. </script>

三、案例——使用AJAX验证用户名是否存在

1c861f69f6b14dc7aee23e15dcd396b9.png

SelectUserSevlet伪代码:

  1. @WebServlet("/selectUserServlet")
  2. public class SelectUserServlet extends HttpServlet {
  3. @Override
  4. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  5. //1. 接收用户名
  6. String username = request.getParameter("username");
  7. //2. 调用service查询User对象
  8. boolean flag = true;//模拟用户名存在
  9. //3. 响应标记
  10. response.getWriter().write("" + flag);
  11. }
  12. @Override
  13. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  14. this.doGet(request, response);
  15. }
  16. }

register.html:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>欢迎注册</title>
  6. <link href="css/register.css" rel="stylesheet">
  7. </head>
  8. <body>
  9. <div class="form-div">
  10. <div class="reg-content">
  11. <h1>欢迎注册</h1>
  12. <span>已有帐号?</span> <a href="login.html">登录</a>
  13. </div>
  14. <form id="reg-form" action="#" method="get">
  15. <table>
  16. <tr>
  17. <td>用户名</td>
  18. <td class="inputs">
  19. <input name="username" type="text" id="username">
  20. <br>
  21. <span id="username_err" class="err_msg" style="display: none">用户名已存在</span>
  22. </td>
  23. </tr>
  24. <tr>
  25. <td>密码</td>
  26. <td class="inputs">
  27. <input name="password" type="password" id="password">
  28. <br>
  29. <span id="password_err" class="err_msg" style="display: none">密码格式有误</span>
  30. </td>
  31. </tr>
  32. <tr>
  33. <td>验证码</td>
  34. <td class="inputs">
  35. <input name="checkCode" type="text" id="checkCode">
  36. <img src="imgs/a.jpg">
  37. <a href="#" id="changeImg">看不清?</a>
  38. </td>
  39. </tr>
  40. </table>
  41. <div class="buttons">
  42. <input value="注 册" type="submit" id="reg_btn">
  43. </div>
  44. <br class="clear">
  45. </form>
  46. </div>
  47. <script>
  48. //1. 给用户名输入框绑定 失去焦点事件
  49. document.getElementById("username").onblur = function () {
  50. //2. 发送ajax请求
  51. // 获取用户名的值
  52. var username = this.value;
  53. //2.1. 创建核心对象
  54. var xhttp;
  55. if (window.XMLHttpRequest) {
  56. xhttp = new XMLHttpRequest();
  57. } else {
  58. // code for IE6, IE5
  59. xhttp = new ActiveXObject("Microsoft.XMLHTTP");
  60. }
  61. //2.2. 发送请求
  62. xhttp.open("GET", "http://localhost:8080/ajax-demo/selectUserServlet?username="+username);
  63. xhttp.send();
  64. //2.3. 获取响应
  65. xhttp.onreadystatechange = function() {
  66. if (this.readyState == 4 && this.status == 200) {
  67. //alert(this.responseText);
  68. //判断
  69. if(this.responseText == "true"){
  70. //用户名存在,显示提示信息
  71. document.getElementById("username_err").style.display = '';
  72. }else {
  73. //用户名不存在 ,清除提示信息
  74. document.getElementById("username_err").style.display = 'none';
  75. }
  76. }
  77. };
  78. }
  79. </script>
  80. </body>
  81. </html>

四、Axios框架

8f3897fed45f4589993ae49478f77078.png

Servlet:

  1. @WebServlet("/axiosServlet")
  2. public class AxiosServlet extends HttpServlet {
  3. @Override
  4. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  5. System.out.println("get...");
  6. //1. 接收请求参数
  7. String username = request.getParameter("username");
  8. System.out.println(username);
  9. //2. 响应数据
  10. response.getWriter().write("hello Axios~");
  11. }
  12. @Override
  13. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  14. System.out.println("post...");
  15. this.doGet(request, response);
  16. }
  17. }

HTML页面:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <body>
  8. <script src="js/axios-0.18.0.js"></script>
  9. <script>
  10. // //1.get
  11. // axios({
  12. // method:"get",
  13. // url:"http://localhost:8080/ajax-demo/axiosServlet?username=zhangsan"
  14. // }).then(function (resp){
  15. // alert(resp.data);
  16. // })
  17. //1.post
  18. axios({
  19. method:"post",
  20. url:"http://localhost:8080/ajax-demo/axiosServlet?username=zhangsan",
  21. data:"username=zhangsan"
  22. }).then(function (resp){
  23. alert(resp.data);
  24. })
  25. </script>
  26. </body>
  27. </html>

8c23cfa260d041b79a8da21c94def78f.png

8c82d2a333e04e63bb913b5ac617a0d4.png

五、JSON

5.1 JSON概述

727b69ea97c64b82a7a56bf0c8f397ae.png

5.2 JSON基础语法

61fb744057e54deda202e143fa220fde.png

5.3 JSON数据和Java对象转换

6df0f3df295f42338933ec440cb58d24.png

4910975b3bdf4906b9da154dc32fd1ed.png

  1. public class FastJsonDemo {
  2. public static void main(String[] args) {
  3. //1.将Java对象转为JSON字符串
  4. User user = new User();
  5. user.setId(1);
  6. user.setUsername("zhangsan");
  7. user.setPassword("123");
  8. String jsonString = JSON.toJSONString(user);
  9. System.out.println(jsonString);
  10. //2.将JSON字符串转为Java对象
  11. User u = JSON.parseObject("{\"id\":1,\"password\":\"123\",\"username\":\"zhangsan\"}",User.class);
  12. System.out.println(u);
  13. }
  14. }

5.4 案例——查询所有(AJAX、JSON)

4820c2da5c184f218fc66f1bc48fb4f0.png

Servlet:

  1. @WebServlet("/selectAllServlet")
  2. public class SelectAllServlet extends HttpServlet {
  3. private BrandService brandService = new BrandService();
  4. @Override
  5. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  6. //1.调用Service查询
  7. List<Brand> brands = brandService.selectAll();
  8. //2.将集合转换为JSON数据 序列化
  9. String jsonString = JSON.toJSONString(brands);
  10. //3.响应数据
  11. response.setContentType("text/json;charset=utf-8");
  12. response.getWriter().write(jsonString);
  13. }
  14. @Override
  15. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  16. this.doGet(request, response);
  17. }
  18. }

brand.html:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <body>
  8. <a href="addBrand.html"><input type="button" value="新增"></a><br>
  9. <hr>
  10. <table id="brandTable" border="1" cellspacing="0" width="100%">
  11. <!-- <tr align="center">-->
  12. <!-- <td>1</td>-->
  13. <!-- <td>三只松鼠</td>-->
  14. <!-- <td>三只松鼠</td>-->
  15. <!-- <td>100</td>-->
  16. <!-- <td>三只松鼠,好吃不上火</td>-->
  17. <!-- <td>启用</td>-->
  18. <!-- <td><a href="#">修改</a> <a href="#">删除</a></td>-->
  19. <!-- </tr>-->
  20. <!-- <tr align="center">-->
  21. <!-- <td>2</td>-->
  22. <!-- <td>优衣库</td>-->
  23. <!-- <td>优衣库</td>-->
  24. <!-- <td>10</td>-->
  25. <!-- <td>优衣库,服适人生</td>-->
  26. <!-- <td>禁用</td>-->
  27. <!-- <td><a href="#">修改</a> <a href="#">删除</a></td>-->
  28. <!-- </tr>-->
  29. <!-- <tr align="center">-->
  30. <!-- <td>3</td>-->
  31. <!-- <td>小米</td>-->
  32. <!-- <td>小米科技有限公司</td>-->
  33. <!-- <td>1000</td>-->
  34. <!-- <td>为发烧而生</td>-->
  35. <!-- <td>启用</td>-->
  36. <!-- <td><a href="#">修改</a> <a href="#">删除</a></td>-->
  37. <!-- </tr>-->
  38. </table>
  39. <script src="js/axios-0.18.0.js"></script>
  40. <script>
  41. //1.当页面加载完成后,发送AJAX请求
  42. window.onload = function (){
  43. //2.发送ajax请求
  44. axios({
  45. method:"get",
  46. url:"http://localhost:8080/brand-demo/selectAllServlet"
  47. }).then(function (resp){
  48. //获取数据
  49. let brands = resp.data;
  50. let tableData = "<tr>\n" +
  51. " <th>序号</th>\n" +
  52. " <th>品牌名称</th>\n" +
  53. " <th>企业名称</th>\n" +
  54. " <th>排序</th>\n" +
  55. " <th>品牌介绍</th>\n" +
  56. " <th>状态</th>\n" +
  57. " <th>操作</th>\n" +
  58. " </tr>";
  59. for (let i = 0; i < brands.length; i++) {
  60. let brand = brands[i];
  61. tableData +=" <tr align=\"center\">\n" +
  62. " <td>"+(i+1)+"</td>\n" +
  63. " <td>"+brand.brandName+"</td>\n" +
  64. " <td>"+brand.companyName+"</td>\n" +
  65. " <td>"+brand.ordered+"</td>\n" +
  66. " <td>"+brand.description+"</td>\n" +
  67. " <td>"+brand.status+"</td>\n" +
  68. "\n" +
  69. " <td><a href=\"#\">修改</a> <a href=\"#\">删除</a></td>\n" +
  70. " </tr>"
  71. }
  72. //设置显示表格数据
  73. document.getElementById("brandTable").innerHTML = tableData;
  74. })
  75. }
  76. </script>
  77. </body>
  78. </html>

5.5 案例——新增品牌

946c004e78cb460bb0357e8898f18a11.png

Servlet:

  1. @WebServlet("/addServlet")
  2. public class AddServlet extends HttpServlet {
  3. private BrandService brandService = new BrandService();
  4. @Override
  5. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  6. //1. 接收数据,request.getParameter 不能接收json的数据
  7. /* String brandName = request.getParameter("brandName");
  8. System.out.println(brandName);*/
  9. // 获取请求体数据
  10. BufferedReader br = request.getReader();
  11. String params = br.readLine();
  12. // 将JSON字符串转为Java对象
  13. Brand brand = JSON.parseObject(params, Brand.class);
  14. //2. 调用service 添加
  15. brandService.add(brand);
  16. //3. 响应成功标识
  17. response.getWriter().write("success");
  18. }
  19. @Override
  20. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  21. this.doGet(request, response);
  22. }
  23. }

html页面:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>添加品牌</title>
  6. </head>
  7. <body>
  8. <h3>添加品牌</h3>
  9. <form action="" method="post">
  10. 品牌名称:<input id="brandName" name="brandName"><br>
  11. 企业名称:<input id="companyName" name="companyName"><br>
  12. 排序:<input id="ordered" name="ordered"><br>
  13. 描述信息:<textarea rows="5" cols="20" id="description" name="description"></textarea><br>
  14. 状态:
  15. <input type="radio" name="status" value="0">禁用
  16. <input type="radio" name="status" value="1">启用<br>
  17. <input type="button" id="btn" value="提交">
  18. </form>
  19. <script src="js/axios-0.18.0.js"></script>
  20. <script>
  21. //1.给button按钮绑定单击事件
  22. document.getElementById("btn").onclick = function (){
  23. //将表单数据转为json
  24. var formData = {
  25. brandName: "",
  26. companyName: "",
  27. ordered: "",
  28. description: "",
  29. status: ""
  30. }
  31. //获取表单数据
  32. let brandName = document.getElementById("brandName").value;
  33. //设置数据
  34. formData.brandName = brandName;
  35. //获取表单数据
  36. let companyName = document.getElementById("companyName").value;
  37. //设置数据
  38. formData.companyName = companyName;
  39. //获取表单数据
  40. let ordered = document.getElementById("ordered").value;
  41. //设置数据
  42. formData.ordered = ordered;
  43. //获取表单数据
  44. let description = document.getElementById("description").value;
  45. //设置数据
  46. formData.description = description; //获取表单数据
  47. let status = document.getElementsByName("status");
  48. for (let i = 0; i < status.length; i++) {
  49. if (status[i].spellcheck){
  50. //
  51. formData.status = status[i].value;
  52. }
  53. }
  54. console.log(formData);
  55. //2.发送ajax请求
  56. axios({
  57. method:"post",
  58. url:"http://localhost:8080/brand-demo/addServlet",
  59. data:formData
  60. }).then(function (resp){
  61. //判断响应数据是否为success
  62. if (resp.data == "success"){
  63. //成功则跳转到品牌列表
  64. location.href = "http://localhost:8080/brand-demo/brand.html"
  65. }
  66. })
  67. }
  68. </script>
  69. </body>
  70. </html>

发表评论

表情:
评论列表 (有 0 条评论,157人围观)

还没有评论,来说两句吧...

相关阅读