Axios异步框架

发布时间 2023-04-11 23:25:13作者: 实名吓我一跳

Axios快速入门

1.引入axios的js文件

<script src="js/axios-0.18.0.js"></script>

2.使用axio发送请求,并响应结果

get:

  axios({
method:"get",
url:"http://localhost:8080/science/axiosServlet?username=zhangsan"
}).then(function (resp)
{
alert(resp.data);
})

post:

axios({
method:"post",
url:"http://localhost:8080/science/axiosServlet",
data:"username=zhangsan"
}).then(function (resp)
{
alert(resp.data);
})
简化:
1.get
axios.get("http://localhost:8080/science/axiosServlet?username=zhangsan").then(function (resp)
{
alert(resp.data);
})
2.axios.post("http://localhost:8080/science/axiosServlet","username=zhangsan").then(function (resp)
{
alert(resp.data);
})

完整代码:

html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>

<script src="js/axios-0.18.0.js"></script>
<script>
// 1.get
// axios({
// method:"get",
// url:"http://localhost:8080/science/axiosServlet?username=zhangsan"
// }).then(function (resp)
// {
// alert(resp.data);
// })
// 1.post
// axios({
// method:"post",
// url:"http://localhost:8080/science/axiosServlet",
// data:"username=zhangsan"
// }).then(function (resp)
// {
// alert(resp.data);
// })
// 1.get
// axios.get("http://localhost:8080/science/axiosServlet?username=zhangsan").then(function (resp)
// {
// alert(resp.data);
// })
axios.post("http://localhost:8080/science/axiosServlet","username=zhangsan").then(function (resp)
{
alert(resp.data);
})
</script>
</body>
</html>
AxiosServlet
public class AxiosServlet extends HttpServlet {
private Service service = new Service();

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// request.setCharacterEncoding("UTF-8");
// String username=request.getParameter("username");
// String password=request.getParameter("password");
System.out.println("get....");
//1.接收参数
String username = request.getParameter("username");
System.out.println(username);
//2 响应数据
response.getWriter().write("hello AxiosServlet~");
//
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("post....");
this.doGet(request, response);
}
}
结果演示:

总结:
Axios 是一个基于 promise 的 HTTP 库,简单的讲就是可以发送get、post请求。