目录
一、Axios概述
二、Axios入门案例
三、Axios请求方式别名
一、Axios概述
Axios对原生的AJAX进行封装,简化书写
Axios 是一个基于 promise 网络请求库,作用于node.js 和浏览器中。 它是 isomorphic 的(即同一套代码可以运行在浏览器和node.js中)。在服务端它使用原生 node.js
http
模块, 而在客户端 (浏览端) 则使用 XMLHttpRequests。
特性
- 从浏览器创建XMLHttpRequests
- 从 node.js 创建http 请求
- 支持Promise API
- 拦截请求和响应
- 转换请求和响应数据
- 取消请求
- 自动转换JSON数据
- 客户端支持防御XSRF
官网地址:起步 | Axios 中文文档 | Axios 中文网 (axios-http.cn)
https://www.axios-http.cn/docs/intro
二、Axios入门案例
1、引入axios的js文件
在html中引入:
<script src="js/axios-0.18.0.js"></script>
2、使用axios发送请求(get及post),并获取响应结果
<script>
//1.get
axios({
method:"get",
url:"http://localhost:8080/ajax-demo/axiosServlet?username=zhangsan"
}).then(function (resp) {
alert(resp.data);
})
//2.post
axios({
method:"post",
url:"http://localhost:8080/ajax-demo/axiosServlet",
data:"username=zhangsan"
}).then(function (resp) {
alert(resp.data);
})
</script>
AxiosServlet代码:
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/axiosServlet")
public class AxiosServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("get...");
//1. 接收请求参数
String username = request.getParameter("username");
System.out.println(username);
//2.响应数据
response.getWriter().write("hello Axios");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("post...");
this.doGet(request, response);
}
}
执行结果:
访问02-axios-demo.html时get请求结果:
访问02-axios-demo.html时post请求结果及控制台结果:
三、Axios请求方式别名
为了方便起见,Axios已经为所有支持的请求方法提供了别名
axios.get(url[,config[)
axios.delete(url[,config])
axios.head(url[,config])
axios.options(url[,config])
axios.post(url[,data[,config]])
axios.put(url[,data[,config]])
axios.patch(url[,data[,config]])
方法名 | 作用 |
get(url) | 发送GET请求 |
post(url,请求参数) | 发送POST方式请求 |
发送get请求
axios.get("url")
.then(function (resp){
alert(resp.data);
});
示例:
axios.get("http://localhost:8080/ajax-demo/axiosServlet?username=zhangsan").then(function (resp) {
alert(resp.data);
})
发送post请求
axios.get("url","参数")
.then(function (resp){
alert(resp.data);
axios.post("http://localhost:8080/ajax-demo/axiosServlet","username=zhangsan").then(function (resp) {
alert(resp.data);
})