//2.2. 发送请求
xhttp.open(“GET”, "http://localhost:8080/ajax-demo/selectUserServlet);
xhttp.send();
//2.3. 获取响应
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//处理响应的结果
}
};
由于我们发送的是 GET 请求,所以需要在 URL 后拼接从输入框获取的用户名数据。而我们在 第一步
绑定的匿名函数中通过以下代码可以获取用户名数据
// 获取用户名的值
var username = this.value; //this : 给谁绑定的事件,this就代表谁
而携带数据需要将 URL 修改为:
xhttp.open(“GET”, “http://localhost:8080/ajax-demo/selectUserServlet?username=”+username);
第三步:处理响应:是否显示提示信息
当 this.readyState == 4 && this.status == 200
条件满足时,说明已经成功响应数据了。
此时需要判断响应的数据是否是 “true” 字符串,如果是说明用户名已经占用给出错误提示;如果不是说明用户名未被占用清除错误提示。代码如下
//判断
if(this.responseText == “true”){
//用户名存在,显示提示信息
document.getElementById(“username_err”).style.display = ‘’;
}else {
//用户名不存在 ,清楚提示信息
document.getElementById(“username_err”).style.display = ‘none’;
}
综上所述,前端完成代码如下:
//1. 给用户名输入框绑定 失去焦点事件
document.getElementById(“username”).onblur = function () {
//2. 发送ajax请求
// 获取用户名的值
var username = this.value;
//2.1. 创建核心对象
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhttp = new ActiveXObject(“Microsoft.XMLHTTP”);
}
//2.2. 发送请求
xhttp.open(“GET”, “http://localhost:8080/ajax-demo/selectUserServlet?username=”+username);
xhttp.send();
//2.3. 获取响应
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//alert(this.responseText);
//判断
if(this.responseText == “true”){
//用户名存在,显示提示信息
document.getElementById(“username_err”).style.display = ‘’;
}else {
//用户名不存在 ,清楚提示信息
document.getElementById(“username_err”).style.display = ‘none’;
}
}
};
}
Axios 对原生的AJAX进行封装,简化书写。
Axios官网是:https://www.axios-http.cn
4.1 基本使用
axios 使用是比较简单的,分为以下两步:
- 引入 axios 的 js 文件
-
使用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
请求,需要将请求参数拼接到路径的后面,格式为:url?参数名=参数值&参数名2=参数值2
。 -
data
属性:作为请求体被发送的数据。也就是说如果是post
请求的话,数据需要作为data
属性的值。
then()
需要传递一个匿名函数。我们将 then()
中传递的匿名函数称为 回调函数,意思是该匿名函数在发送请求时不会被调用,而是在成功响应后调用的函数。而该回调函数中的 resp
参数是对响应的数据进行封装的对象,通过 resp.data
可以获取到响应的数据。
4.2 快速入门
4.2.1 后端实现
定义一个用于接收请求的servlet,代码如下:
@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,