Axios,是一个基于promise的网络请求库,作用于node.js和浏览器中。在服务端它使用原生node.js http模块, 而在客户端 (浏览端) 则使用XMLHttpRequest。可以理解为Axios是对原生的AJAX进行封装,简化书写。
Axios官网:Axios
1.基本使用
- 引入axios的js文件
<script src="js/axios-0.18.0.js"></script>
-
使用axios 发送请求,并获取响应结果
axios()
是用来发送异步请求的,小括号中使用 js 对象传递请求相关的参数:- 发送get请求,数据在url中
//1.get axios({ method:"get", //请求方式,get/post url:"http://localhost:8080/ajax-demo/axiosServlet?username=zhangsan" }).then(function (resp){ //resp---->response alert(resp.data); })
- 发送post请求,数据在data中
axios({ method:"post", url:"http://localhost:8080/ajax-demo/axiosServlet", data:"username=zhangsan" //post请求才有 }).then(function (resp){ alert(resp.data); })
then()
需要传递一个匿名函数。我们将 then()
中传递的匿名 函数称为 回调函数,意思是该匿名函数在发送请求时不会被调用, 而是在成功响应后调用的函数。而该回调函数中的 resp
参数是对 响应的数据进行封装的对象,通过 resp.data
可以获取到响应的数 据。
2.get和post请求方法别名
- get请求:
axios.get(url[,config])
axios.get("http://localhost:8080/ajax-demo/axiosServlet?username=zhangsan").then(function (resp){
alert(resp.data);
})
- post请求:
axios.post(url[,data[,config])
axios.post("http://localhost:8080/ajax-demo/axiosServlet","username=zhangsan").then(function (resp){
alert(resp.data);
})