Ajax框架Axios的基本使用
axios的基本使用
axios的使用非常简单:
-
第一步,引入 axios 的 js 文件 <script src="js/axios-0.18.0.js"></script> 第二部,使用axios 发送请求,并获取响应结果 发送 get 请求 axios({ method:"get", url:"http://localhost:8080/ajax-demo1/aJAXDemo1?username=zhangsan" }).then(function (resp){ alert(resp.data); }) 发送 post 请求 axios({ method:"post", url:"http://localhost:8080/ajax-demo1/aJAXDemo1", data:"username=zhangsan" }).then(function (resp){ alert(resp.data); });
axios() 是用来发送异步请求的,小括号中使用 js 对象传递请求相关的参数: method属性设置请求方式,取值为GET,POST等; url属性用于设置请求资源路径,注意如果是GET请求需要把请求参数拼接在请求路径的后面 data属性用于设置请求参数,请求方式为post,可以使用此属性设置参数 then() 需要传递一个匿名函数。我们将 then() 中传递的匿名函数称为 回调函数,意思是该匿名函数在发送请求时不会被调用,而是在成功响应后调用的函数。而该回调函数中的 resp 参数是对响应的数据进行封装的对象,通过 resp.data 可以获取到响应的数据。
掌握了以上的axios知识通过一个小案例来巩固一下:
axios+servlet小案例
需求: 使用post方式向服务器发送tomcat请求,要求携带参数username=“zhangsan”,并将请求参数通过servlet在控制台上打印出来,还有将请求参数通过服务器响应给客户端 前端实现
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="js/axios-0.18.0.js"></script> </head> <body> <script> axios({ method:"post", url:"http://localhost:8080/ajax-axios-demo/axiosDemoServlet", data:"username=zhangsan" }).then(function(resp){ alert(resp.data); }); </script> </body> </html>
后端实现
@WebServlet("/axiosDemoServlet") public class AxiosDemoServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取请求参数 String username = request.getParameter("username"); System.out.println("获取请求参数:"+username); response.getWriter().write("username="+username); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
在浏览器输入: http://localhost:8080/ajax-axios-demo/demo1.html 查看响应结果: 看控制台输出: 至此axios的使用我们已经介绍完了,拜拜😄
上一篇:
通过多线程提高代码的执行效率例子
下一篇:
Vue配置反向代理解决跨域问题