Ajax异步请求 axios
Ajax异步请求 axios
1 axios介绍
-
原生ajax请求的代码编写太过繁琐,我们可以使用axios这个库来简化操作!
在后续学习的Vue(前端框架)中发送异步请求,使用的就是axios.
需要注意的是axios不是vue的插件,它可以独立使用.
axios说明网站:(https://www.kancloud.cn/yunye/axios/234845)
-
使用步骤
1.引入axios核心js文件。2.使用axios对象调用方法来发起异步请求。
3.使用axios对象调用方法来处理响应的数据。 -
axios常用方法
http://www.baidu.com?username=锁哥 ==》get请求
回调函数:回过头来调用的函数,回调函数都是我们负责书写,不负责调用,都是底层帮助我们调用。
setInterval(function(){},1000);
#备注: then函数的参数response是一个json对象,我们重点只需要了解response.data即可 {// `data` 由服务器提供的响应 (重要!) response.datadata: {},// `status` 来自服务器响应的 HTTP 状态码 response.statusstatus: 200,// `statusText` 来自服务器响应的 HTTP 状态信息statusText: 'OK',// `headers` 服务器响应的头headers: {},// `config` 是为请求提供的配置信息config: {} }
-
代码实现
- get请求
- axios使用说明:
/** # axios的api介绍* 1. get(参数) 建立和服务器的连接* get参数 : 是请求地址+请求参数 ---url?key=value&key=value...* 2. then(fn) 处理服务器响应* fn(response) : 响应成功的回调函数* response.data : 响应体数据** 3. catch(fn)* fn(error) : 响应失败的的回调函数* error : 错误信息** 4. finally(fn)* fn : 响应结束的回调函数(无论响应成功与否,都会执行)* */ 整体代码,链式编程: // /AjaxServlet 表示后台服务器地址 url // name=zs&age=18 表示向后台提交的数据,get请求数据位于url后面,携带数据格式:url?key=value&key=value axios.get("/AjaxServlet?name=zs&age=18").then(function (response) {// 回调函数的函数体,处理后台服务器的响应的代码,所有的数据都放到response对象中了,注意response只是一个对象标识符,名字随便定义,我们只负责编写匿名函数体代码}).catch(function (error) {// 回调函数的函数体,如果后台服务器出现异常就在这里处理,所有的错误信息放到error对象中};).finally(function () {// 回调函数的函数体,必须执行的代码};);=================使用es6的箭头函数简================================================()=>{} axios.get("/AjaxServlet?name=zs&age=18").then(response=>{// 回调函数的函数体,处理后台服务器的响应的代码,所有的数据都放到response对象中了,注意response只是一个对象标识符,名字随便定义,我们只负责编写匿名函数体代码}).catch(error=>{// 回调函数的函数体,如果后台服务器出现异常就在这里处理,所有的错误信息放到error对象中};).finally(() => {// 回调函数的函数体,必须执行的代码};);
代码实现:
步骤:
1.导入axios的js库到当前项目webapp文件夹下
2.创建html页面
3.在html页面中导入axios的js库
4.在html页面向后台发送axios的ajax异步请求
5.创建Servlet,接收请求数据,处理业务逻辑和响应数据
6.在html页面中处理服务器的响应数据
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>使用axios发送异步请求</title> </head> <body> <!-- 不能在文本中书写js代码--> <script type="text/javascript" src="js/axios-0.18.0.js"></script> <script type="text/javascript">//1.使用axios对象调用函数向后台服务器发送ajax异步请求/*整体: axios.get().then().catch().finally();1)get()函数表示两后台服务器发送get请求,格式:get(url?key=value&key=value...);===axios.get("/axiosDemo01Servlet?username=锁哥&password=1234")2)then() 处理后台服务器响应的,格式:then(function(接收响应数据的对象名){处理响应的代码});then(function (resp){console.log(resp);})后台响应数据:resp={data: 'axios实现ajax异步get请求,username=锁哥',status: 200,statusText: '',headers: {…},config: {…},}resp.data就可以获取 数据: axios实现ajax异步get请求,username=锁哥3)catch() :处理异常catch(function (error) {console.log(error);})let person ={username:"锁哥",age:18}小结:1.get函数:建立和服务器的连接,在参数中书写连接服务器的url和请求参数2.then函数:书写处理响应数据的,在该函数的参数位置书写回调函数3.catch函数:书写处理响应错误信息数据的,在该函数的参数位置书写回调函数4.finally函数:无论响应成功还是失败都要执行的代码,在该函数的参数位置书写回调函数*/axios.get("http://localhost:8080/axiosDemo01Servlet?username=锁哥&password=1234").then(function (response) {//处理响应数据的回调函数体代码,response表示接受服务器响应数据的对象,该对象中具有重要属性是dataconsole.log(response);console.log(response.data);}).catch(function (error) {//书写处理响应错误信息数据的,在该函数的参数位置书写回调函数console.log(error);}).finally(function () {//无论响应成功还是失败都要执行的代码,在该函数的参数位置书写回调函数console.log('我是必须执行的...');}); </script> </body> </html>
- get请求
【后台代码,先不用理会,后面会讲解】
# 说明:对于后台代码我们不用理会,但是我们需要启动后台,如果不启动后台,前端是无法访问后台的。前端这几天启动后台基本都是一样的方式,如下:
- 1.找到课后资料中的目录:
day03-AJAX&Vue\02_代码\授课素材\01_ajax素材\异步\后端
- 2.在上述目录下输入cmd命令打开dos窗口
- 3.在dos窗口中输入jdk命令来启动项目:
java -jar day0302_ajax.jar
ps:使用java命令运行jar包:java -jar 项目的jar包
说明:1)java -jar 属于java中命令,执行jar包的 2)day0302_ajax.jar 是上述目录中后台项目的jar包
- 停止后台项目运行:ctrl+c
package com.itheima.sh.a_axios_01;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("/axiosDemo01Servlet")
public class AxiosDemo01Servlet extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet(request, response);}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//1.获取请求数据// axios.get("/axiosDemo01Servlet?username=锁哥&password=1234")//.getParameter("username"); 函数的参数username是前端get函数中url后面参数的keyString username = request.getParameter("username");String password = request.getParameter("password");//2.输出System.out.println(username+"---"+password);//模拟异常:
// int i = 1 / 0;//3.响应数据给前端response.getWriter().print("axios实现ajax异步get请求,username="+username);}
}
小结:
1.使用axios发送ajax的异步请求:
1.导入axios的js库
<script type="text/javascript" src="js/axios-0.18.0.js"></script>
2.使用axios对象调用方法进行发送请求和处理响应数据:
axios.get("url?key=value&key=value").then(function(response){//处理响应代码
}).catch(function(error){//处理响应代码,错误信息
}).finally(function(){//必须执行的
});
- post请求
- axios使用说明:
/** 1. post(url,param)* url : 请求地址(不能包含请求参数)* param : 请求参数(走请求体) key=value&key=value... 如果不携带参数那么书写: axios.post(url).then()...** 2. 箭头函数 (相当于java中的lambda表达式)* es6的新语法 !!!* //普通函数* function(response){console.log(response.data) // 响应体数据}//箭头函数 :(参数名,参数名,...) => {函数体}//如果参数只有一个那么可以省略小括号response => {console.log(response.data)}注意:考虑后期学习的vue框架我们建议都使用箭头函数。* */
整体代码,链式编程:axios.post(url, param).then(response => {// 回调函数的函数体,后台响应成功执行then函数}).catch(error => {// 回调函数的函数体}).finally(() => {// 回调函数的函数体});
代码实现:
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>使用axios发送异步请求</title>
</head>
<body>
<!-- 不能再文本中书写js代码-->
<script type="text/javascript" src="js/axios-0.18.0.js"></script>
<script type="text/javascript">//1.使用axios对象调用函数向后台服务器发送ajax异步请求/*整体: axios.post().then().catch().finally();1)post()函数表示向后台服务器发送post请求,格式:post(url,key=value&key=value...);===axios.post("/axiosDemo01Servlet","username=锁哥&password=1234")2)then() 处理后台服务器响应的,格式:then(function(接收响应数据的对象名){处理响应的代码});其实在then函数中的回调函数我们可以使用es6的新语法,箭头函数:(参数)=>{函数体}格式:then(resp=>{函数体});*//*说明:1.http://localhost:8080/axiosDemo03Servlet 表示后台服务器地址2.username=锁哥&password=1234:表示向后台携带的参数*///使用es6的箭头函数简化上述回调函数的写法axios.post("http://localhost:8080/axiosDemo03Servlet","username=锁哥&password=1234").then(response=>{console.log(response.data);}).finally(()=>{console.log('必须执行的');});</script>
</body>
</html>
- java代码【后台代码,先不用理会,后面会讲解】
package com.itheima.sh.a_axios_01;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("/axiosDemo03Servlet")
public class AxiosDemo03Servlet extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet(request, response);}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//1.获取请求数据// axios.post("/axiosDemo02Servlet","username=锁哥&password=1234")//.getParameter("username"); 函数的参数username是前端post函数中url后面参数的keyString username = request.getParameter("username");String password = request.getParameter("password");//2.输出System.out.println(username+"---"+password);//3.响应数据response.getWriter().print("axios实现ajax异步post请求,username="+username);}
}
小结:
1.如果使用的是axios的post请求,那么必须在post函数中将url和请求参数分开书写:
axios.post("http://localhost:8080/axiosDemo03Servlet", "username=锁哥&password=1234")
2.我们对于需要使用回调函数的位置可以使用es6的箭头函数简化代码书写:
axios.post("/axiosPostServlet", "username=锁哥&password=1234").then(response=>{//response属于标识符,随便定义console.log(response.data);}).finally(()=>{console.log('必须执行的');});
3.箭头函数体省略书写,思想和java中lambda省略思想是一样的:
axios.post("/axiosPostServlet", "username=锁哥&password=1234").then(response=>console.log(response.data)).finally(()=>{console.log('必须执行的');});
2 练习:检查用户名是否已被注册
【1】需求
#需求: a. 有一个注册的表单, 有注册用户名和密码,一个提交按钮b. 用户名输完之后,检测这个用户名是否可用c. 就算服务器没有立即响应, 用户还能继续在表单上操作 -> 异步
【2】分析
#分析:1. 用户名输入框注册一个失去焦点事件(onblur)2. 向服务器发送 异步 请求3. 服务器响应之后, 提示信息 局部更新到页面上
【3】html代码
/** 需求: 查看此用户名是否已注册* 分析:* 1. 前提: 注册的用户存到数据库中了* 2. 判断: 数据库中是否有这个用户名* 1). 如果有, 提示已被注册不可用* 2). 如果没有, 提示可用** 前端: 发起请求* 事件: onblur* 1). 请求的类型: 异步 (不跳转而且只要页面局部更新)* 2). axios* a. 请求地址* b .请求参数** 后端: 接收请求,业务处理,响应数据* 1). 获取请求参数* 2). 查询数据库* 3). 根据结果响应** 前端: 接收响应, 显示数据** */
【4】步骤
#前端
1.创建一个html页面,书写html标签
2.在html页面中导入axios的js库
3.使用js获取用户名输入框的标签对象并给其绑定一个离焦事件onblur
4.在离焦事件绑定的匿名函数体中获取页面输入的用户名
5.使用axios向后台发送异步请求并携带用户名数据到后台服务器
6.在axios的回调函数中处理后台响应的数据
7.根据响应的结果进行判断
8.用户名存在,不能注册,提示用户名已经存在
9.用户名不存在,可以注册,提示可以注册#后台
1.创建注册的servlet
2.处理请求乱码
3.获取页面提交的请求参数
4.模拟数据库判断获取的数据是否存在
5.响应数据给前端页面
【5】代码实现
<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body>
<form action=""><input type="text" name="username" placeholder="请输入用户名" id="username"><span id="usernameSpan"></span><br><input type="password" name="password" placeholder="请输入密码"> <br><button>提交</button>
</form>
</body></html>
<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body>
<form action=""><input type="text" name="username" placeholder="请输入用户名" id="username"><span id="usernameSpan"></span><br><input type="password" name="password" placeholder="请输入密码"> <br><button>提交</button>
</form>
<!-- 导入axios类库 -->
<script type="text/javascript" src="js/axios-0.18.0.js"></script>
<script type="text/javascript">/*说明:1.后台地址url:"http://localhost:8080/registerServlet"2.后台需要根据key即参数名是username来获取前端提交的用户名数据*///3.使用js获取用户名输入框的标签对象并给其绑定一个离焦事件onblurdocument.getElementById('username').onblur = function () {//4.在离焦事件绑定的匿名函数体中获取页面输入的用户名let username = this.value;//5.使用axios向后台发送异步请求并携带用户名数据到后台服务器//"username="+username 等号左边的username需要后台根据该username获取页面输入的值,等号右边的username是上述保存用户名的变量axios.post("http://localhost:8080/registerServlet","username="+username).then(resp=>{// 6.在axios的回调函数中处理后台响应的数据let result = resp.data;//7.根据响应的结果进行判断if(result == false){//8.用户名存在,不能注册,提示用户名已经存在document.getElementById('usernameSpan').innerHTML="<font color='red'>用户名存在,重新输入</font>"}else {//9.用户名不存在,可以注册,提示可以注册document.getElementById('usernameSpan').innerHTML="<font color='green'>注册成功</font>"}});};</script>
</body>
</html>
servlet代码【后台代码,先不用理会,后面会讲解】
package com.itheima.sh.a_axios_01;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("/registerServlet")
public class RegisterServlet extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet(request, response);}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//1.获取请求参数//后台如何获取usernameValue的值:request.getParameter("username");String username = request.getParameter("username");//2.将获取的name值传递到service层,这里我们暂时不写了,判断if("岩岩".equals(username)){//响应数据,说明用户名存在,不能注册response.getWriter().print(false);}else{//响应数据,说明用户名不存在,能注册response.getWriter().print(true);}}
}