image.png

Axios异步框架使用:

image.png

前端ajax代码

  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. // 2. post
  18. axios({
  19. method:"post",
  20. url:"http://localhost:8080/ajax-demo/axiosServlet",
  21. data:"username=zhangsan"
  22. }).then(function (resp) {
  23. alert(resp.data)
  24. })
  25. </script>
  26. </body>
  27. </html>

后端servlet代码

  1. package com.itheima.web.servlet;
  2. import javax.servlet.ServletException;
  3. import javax.servlet.annotation.WebServlet;
  4. import javax.servlet.http.HttpServlet;
  5. import javax.servlet.http.HttpServletRequest;
  6. import javax.servlet.http.HttpServletResponse;
  7. import java.io.IOException;
  8. @WebServlet("/axiosServlet")
  9. public class AxiosServlet extends HttpServlet {
  10. @Override
  11. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  12. System.out.println("get...");
  13. // 1. 接收请求参数
  14. String username = request.getParameter("username");
  15. System.out.println(username);
  16. // 2. 响应数据
  17. response.getWriter().write("hello Axios");
  18. }
  19. @Override
  20. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  21. System.out.println("post...");
  22. this.doGet(request,response);
  23. }
  24. }

Axios请求方式别名

image.png

运行代码

image.png