ajax

axios(ajax)发送请求

ajax概述

Ajax即Asynchronous Javascript And XML(异步JavaScript和XML)在 2005年被Jesse James Garrett提出的新术语,用来描述一种使用现有技术集合的‘新’方法,包括: HTML 或 XHTML, CSS, JavaScript, DOM, XML, XSLT, 以及最重要的XMLHttpRequest。 [3] 使用Ajax技术网页应用能够快速地将增量更新呈现在用户界面上,而不需要重载(刷新)整个页面,这使得程序能够更快地回应用户的操作。
参考 原生ajax:https://www.runoob.com/php/php-ajax-intro.html

axios 介绍

1.axios 是一个专注于网络请求的库,核心负责发请求和拿数据
在后面的vue react都会用axios来请求数据(类似于后端 httpclient)
2.Axios,是一个基于promise [5] 的网络请求库,作用于node.js浏览器中,它是 isomorphic 的(即同一套代码可以运行在浏览器和node.js中)。在服务端它使用原生node.js http模块, 而在客户端 (浏览端) 则使用XMLHttpRequest。
3.https://www.axios-http.cn/

axios 发送get/post请求

页面引入axios cdn依赖
](https://unpkg.com/axios/dist/axios.min.js">)

  1. <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  2. // 1. 调用 axios 方法得到的返回值是 Promise 对象
  3. axios({
  4. // 请求方式
  5. method: 'GET',
  6. // 请求的地址
  7. url: '接口地址',
  8. // URL 中的查询参数
  9. params: {
  10. id: 1
  11. }
  12. }).then(function (result) {
  13. console.log(result)
  14. })
  1. <%--
  2. Created by IntelliJ IDEA.
  3. User: mayikt
  4. Date: 2022/6/8
  5. Time: 15:48
  6. To change this template use File | Settings | File Templates.
  7. --%>
  8. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  9. <html>
  10. <head>
  11. <title>axios</title>
  12. <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  13. <script>
  14. function mayiktAxios() {
  15. // 1. 调用 axios 方法得到的返回值是 Promise 对象
  16. axios({
  17. // 请求方式
  18. method: 'GET',
  19. // 请求的地址
  20. url: 'http://localhost:8080/${pageContext.request.contextPath}/axiosServlet',
  21. // URL 中的查询参数
  22. params: {
  23. name: "mayikt",
  24. age: 22
  25. }
  26. }).then(function (result) {
  27. alert(result.data);
  28. })
  29. }
  30. </script>
  31. </head>
  32. <body>
  33. <input type="button" value="发送ajax" onclick="mayiktAxios()"/>
  34. </body>
  35. </html>
  1. package com.mayikt.servlet;
  2. import jakarta.servlet.ServletException;
  3. import jakarta.servlet.annotation.WebServlet;
  4. import jakarta.servlet.http.HttpServlet;
  5. import jakarta.servlet.http.HttpServletRequest;
  6. import jakarta.servlet.http.HttpServletResponse;
  7. import java.io.IOException;
  8. import java.io.PrintWriter;
  9. /**
  10. * @author 余胜军
  11. * @ClassName AxiosServlet
  12. * @qq 644064779
  13. * @addres www.mayikt.com
  14. * 微信:yushengjun644
  15. */
  16. @WebServlet("/axiosServlet")
  17. public class AxiosServlet extends HttpServlet {
  18. @Override
  19. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  20. doGet(req, resp);
  21. }
  22. @Override
  23. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  24. PrintWriter writer = resp.getWriter();
  25. String name = req.getParameter("name");
  26. String age = req.getParameter("age");
  27. writer.print("mayikt,name:" + name + ",age:" + age);
  28. writer.close();
  29. }
  30. }

axios验证用户名称是否存在

需求:当我们用户输入用户名称之后(会使用ajax验证用户名称是否已经存在 如果存在的话 则提示 该用户名称是已经存在的)

onkeyup—-监听用户输入完内容 走监听方法

  1. package com.mayikt.servlet;
  2. import com.mayikt.entity.MayiktUserEntity;
  3. import com.mayikt.service.MayikUsertService;
  4. import jakarta.servlet.ServletException;
  5. import jakarta.servlet.annotation.WebServlet;
  6. import jakarta.servlet.http.HttpServlet;
  7. import jakarta.servlet.http.HttpServletRequest;
  8. import jakarta.servlet.http.HttpServletResponse;
  9. import java.io.IOException;
  10. import java.io.PrintWriter;
  11. /**
  12. * http://localhost:8080/mayikt_session_war_exploded/exUserNameServlet?name=1
  13. * @author 余胜军
  14. * @ClassName ExUserNameServlet
  15. * @qq 644064779
  16. * @addres www.mayikt.com
  17. * 微信:yushengjun644
  18. */
  19. @WebServlet("/exUserNameServlet")
  20. public class ExUserNameServlet extends HttpServlet {
  21. private MayikUsertService mayikUsertService = new MayikUsertService();
  22. @Override
  23. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  24. resp.setContentType("text/html;charset=utf-8");
  25. //1.获取到用户输入的userName参数值
  26. String userName = req.getParameter("userName");
  27. //2.调用数据库根据userName查询用户名称是否存在
  28. MayiktUserEntity mayiktUserEntity = mayikUsertService.findByUserName(userName);
  29. PrintWriter writer = resp.getWriter();
  30. if (mayiktUserEntity != null) {
  31. writer.print("该用户" + userName + "已经存在的 无法注册!");
  32. }
  33. writer.close();
  34. }
  35. }
  1. <%--
  2. Created by IntelliJ IDEA.
  3. User: mayikt
  4. Date: 2022/6/6
  5. Time: 17:12
  6. To change this template use File | Settings | File Templates.
  7. --%>
  8. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  9. <!DOCTYPE html>
  10. <html>
  11. <head>
  12. <title>注册页面</title>
  13. <form action="/mayikt_session_war_exploded/register" method="post">
  14. <label>用户名: </label><input type="text" name="userName" onkeyup="mayiktAxios(this)"/><br>
  15. <label>密&nbsp&nbsp&nbsp码: </label><input type="password" name="userPwd"/><br>
  16. <label>验证码: </label><input type="text" name="code"/><img id="exchangecode" src="VerifycodeServlet">
  17. <a id="ecode" href="#">看不清?换一张图片</a><br>
  18. <span id="error" style="color: red">${errorMsg}</span>
  19. <input type="submit" value="注册"/>
  20. </form>
  21. <script type="text/javascript">
  22. window.onload = function () {
  23. //获取img标签的对象
  24. img = document.getElementById("exchangecode");
  25. img.onclick = function () {
  26. //加时间戳,避免浏览器缓存
  27. var date = new Date().getTime()
  28. img.src = "VerifycodeServlet?" + date;
  29. }
  30. //获取a标签的对象
  31. ec = document.getElementById("ecode");
  32. ec.onclick = function () {
  33. //加时间戳
  34. var date = new Date().getTime()
  35. img.src = "VerifycodeServlet?" + date;
  36. }
  37. }
  38. </script>
  39. <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  40. <script>
  41. function mayiktAxios(object) {
  42. // 1.接受用户输入的userName
  43. var userName = object.value;
  44. // 2.使用Axios 发送ajax请求验证 userName是否存在的
  45. axios({
  46. // 请求方式
  47. method: 'GET',
  48. // 请求的地址
  49. url: 'http://localhost:8080${pageContext.request.contextPath}/exUserNameServlet',
  50. // URL 中的查询参数
  51. params: {
  52. userName: userName,
  53. }
  54. }).then(function (result) {
  55. //定位 span id 名称 error 修改
  56. document.getElementById("error").innerText = result.data;
  57. })
  58. }
  59. </script>
  60. </head>
  61. </html>

json

json基础语法

JSON: JavaScript Object Notation(JavaScript 对象表示法);
JSON 是存储和交换文本信息的语法。类似 XML;
JSON —-数据交换格式
客户端与服务器端之间通讯 —-数据交换格式
JSON 体积XML 更小减少带宽传输
JSON 比 XML 更小、更快,更易解析;
json对象
{
name:”mayikt”,
age:22,
isFlag:true
}
如果该json值是为最后一个的情况下 不需要写,
json数组
[
{
name:”mayikt1”,
age:22,
isFlag:true
},
{
name:”mayikt2”,
age:22,
isFlag:true
}
]
{
code:200,
msg:”ok”,
data:[
{
name:”mayikt2”,
age:22,
isFlag:true
},
{
name:”mayikt2”,
age:22,
isFlag:true
}
]
}

1、JSON是由键值对构成的;
2、键要用引号(单双都行)引起,也可以不引;
3、取值范围:
数字(整数或浮点数)
字符串(在双引号中)
逻辑值(true 或 false)
数组(在中括号中)
对象(在大括号中)
null,不常用

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>jsonDemo</title>
  6. <script>
  7. // 1.定义json
  8. var json1 = {name: "mayikt", age: 22, isFlag: true};
  9. alert(json1.name);
  10. alert(json1.age);
  11. alert(json1.isFlag);
  12. // 2.定义json数组
  13. var jsonArr = {code: 200, data: [{name: "mayikt", age: 22}, {name: "meite", age: 22}]};
  14. alert(jsonArr.code);
  15. alert(jsonArr.data[0].name);
  16. var userArr = jsonArr.data;
  17. for (var i = 0; i < userArr.length; i++) {
  18. alert(userArr[i].name + "," + userArr[i].age);
  19. }
  20. </script>
  21. </head>
  22. <body>
  23. </body>
  24. </html>

fastjson用法

常见解析器:JsonLib,Gson,fastjson(阿里),jackson(Spring MVC内置解析器)
文档:javaweb开发相关资料下载.notea
链接:http://note.youdao.com/noteshare?id=61e2cc939390acc9c7e5017907e98044&sub=DAABBA2F350445D2AC6879CCC3F46EA7
image.png

  1. package com.mayikt;
  2. import com.alibaba.fastjson.JSONObject;
  3. import com.mayikt.entity.MayiktUserEntity;
  4. import java.util.ArrayList;
  5. /**
  6. * @author 余胜军
  7. * @ClassName Test01
  8. * @qq 644064779
  9. * @addres www.mayikt.com
  10. * 微信:yushengjun644
  11. */
  12. public class Test01 {
  13. public static void main(String[] args) {
  14. //1.将数据对象变成json(字符串类型)
  15. MayiktUserEntity user1 = new MayiktUserEntity(1, "mayikt", "mayikt");
  16. MayiktUserEntity user2 = new MayiktUserEntity(1, "mayikt", "mayikt");
  17. String json1 = JSONObject.toJSONString(user1);
  18. System.out.println(json1);
  19. //2.嵌套json
  20. JSONObject jsonObject = new JSONObject();
  21. jsonObject.put("code", 200);
  22. jsonObject.put("msg", "ok");
  23. //data值 数组类型
  24. ArrayList<MayiktUserEntity> mayiktUserEntities = new ArrayList<>();
  25. mayiktUserEntities.add(user1);
  26. mayiktUserEntities.add(user2);
  27. jsonObject.put("data", mayiktUserEntities);
  28. System.out.println(jsonObject.toJSONString());
  29. }
  30. }
  31. package com.mayikt;
  32. import com.alibaba.fastjson.JSONArray;
  33. import com.alibaba.fastjson.JSONObject;
  34. import com.alibaba.fastjson.JSONPObject;
  35. import com.mayikt.entity.MayiktUserEntity;
  36. /**
  37. * @author 余胜军
  38. * @ClassName Test02
  39. * @qq 644064779
  40. * @addres www.mayikt.com
  41. * 微信:yushengjun644
  42. */
  43. public class Test02 {
  44. public static void main(String[] args) {
  45. String jsonStr = "{\"msg\":\"ok\",\"code\":200,\"data\":[{\"id\":1,\"userName\":\"mayikt\",\"userPwd\":\"mayikt\"},{\"id\":1,\"userName\":\"mayikt\",\"userPwd\":\"mayikt\"}]}";
  46. // string类型-----jsonobject----jsonobject
  47. JSONObject jsonObject = JSONObject.parseObject(jsonStr);
  48. // Integer code = (Integer) jsonObject.get("code");
  49. Integer code = jsonObject.getInteger("code");
  50. String msg = jsonObject.getString("msg");
  51. System.out.println(code + "," + msg);
  52. JSONArray data = jsonObject.getJSONArray("data");
  53. for (int i = 0; i < data.size(); i++) {
  54. JSONObject object = (JSONObject) data.get(i);
  55. Integer id = object.getInteger("id");
  56. String userName = object.getString("userName");
  57. String userPwd = object.getString("userPwd");
  58. MayiktUserEntity mayiktUserEntity = new MayiktUserEntity(id, userName, userPwd);
  59. System.out.println(mayiktUserEntity);
  60. }
  61. }
  62. }
  63. package com.mayikt;
  64. import com.alibaba.fastjson.JSONObject;
  65. import com.mayikt.entity.Result;
  66. /**
  67. * @author 余胜军
  68. * @ClassName Test03
  69. * @qq 644064779
  70. * @addres www.mayikt.com
  71. * 微信:yushengjun644
  72. */
  73. public class Test03 {
  74. public static void main(String[] args) {
  75. String jsonStr = "{\"msg\":\"ok\",\"code\":200,\"data\":[{\"id\":1,\"userName\":\"mayikt\",\"userPwd\":\"mayikt\"},{\"id\":1,\"userName\":\"mayikt\",\"userPwd\":\"mayikt\"}]}";
  76. JSONObject jsonObject = JSONObject.parseObject(jsonStr);
  77. Result result = JSONObject.parseObject(jsonStr, Result.class);
  78. // java序列化技术 将 json变成对象
  79. System.out.println(result);
  80. }
  81. }
  82. package com.mayikt.entity;
  83. import java.util.List;
  84. /**
  85. * @author 余胜军
  86. * @ClassName Result
  87. * @qq 644064779
  88. * @addres www.mayikt.com
  89. * 微信:yushengjun644
  90. */
  91. public class Result {
  92. private Integer code;
  93. private String msg;
  94. private List<MayiktUserEntity> data;
  95. public Integer getCode() {
  96. return code;
  97. }
  98. public void setCode(Integer code) {
  99. this.code = code;
  100. }
  101. public String getMsg() {
  102. return msg;
  103. }
  104. public void setMsg(String msg) {
  105. this.msg = msg;
  106. }
  107. public List<MayiktUserEntity> getData() {
  108. return data;
  109. }
  110. public void setData(List<MayiktUserEntity> data) {
  111. this.data = data;
  112. }
  113. @Override
  114. public String toString() {
  115. return "Result{" +
  116. "code=" + code +
  117. ", msg='" + msg + '\'' +
  118. ", data=" + data +
  119. '}';
  120. }
  121. }
  1. axios({
  2. method: "post",
  3. url: "${pageContext.request.contextPath}/user/addUser",
  4. data: JSON.stringify(userList),
  5. headers: {
  6. 'Content-Type': 'application/json;charset=UTF-8'
  7. }
  8. }).then(resp => {
  9. })