AJAX 简明笔记

AJAX 简介

AJAX(Asynchronous JavaScirpt And XML):异步 的 JavaScript 和 XML

同步和异步的比较如图所示
03-同步和异步的比较.png

AJAX 作用:

  1. 与服务器进行数据交换:通过 AJAX 可以给服务器发送请求,并获取服务器响应的数据
    1. 使用 AJAX 和服务器进行通信,就可以使用 HTML+AJAX 来替换 JSP 页面了
    2. 使用它的一个重要原因是可以用来替换 JSP 页面;JSP 做不到前后端分离
  2. 异步交互:可以在 不重新加载整个页面 的情况下,与服务器交换数据并 更新部分 网页端技术,如:搜索联想,用户名是否可用校验等等

之前的做法:JSP
01-响应请求JSP做法.png

现在的做法:AJAX
02-响应请求AJAX做法.png

AJAX 快速入门

  1. 编写 AjaxServlet,并使用 response 输出字符串(后端代码)
  2. 创建 XMLHttpRequest 对象:损失和服务器交换数据(前端代码)
  3. 想服务器发送请求(前端代码)
  4. 获取服务器响应数据(前端代码)

一、编写 AjaxServlet,并使用 response 输出字符串

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@WebServlet("/ajaxServlet")  
public class AjaxServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

//1.响应数据
response.getWriter().write("hello AJAX");
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}

二、创建核心对象

1
2
3
4
5
6
7
var xhttp;  
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}

代码可参考 W3C:AJAX - XMLHttpRequest 对象

三、发送请求

1
2
xhttp.open("GET", "http://localhost:8080/ajax-dmeo/ajaxServlet");
xhttp.send();

注意:这里的路径是全路径,因为后期项目的前端和后端需要部署在不同的服务器上,需要使用绝对路径而不是相对路径

代码可参考 W3C:AJAX - XMLHttpRequest

四、获取响应

1
2
3
4
5
xhttp.onreadystatechange = function() {  
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText)
}
};

代码参考 W3C:AJAX - 服务器响应

AJAX 完整案例

注意:还需要我们在服务器端创建一个用于响应浏览器的 Servlet,如以上步骤一所示(一、编写 AjaxServlet,并使用 response 输出字符串)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<!DOCTYPE html>  
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>

<script>
//1.创建核心对象
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}

//2.发送请求
xhttp.open("GET", "http://localhost:8080/ajax-dmeo/ajaxServlet");
xhttp.send();

//3.获取响应
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText)
}
};
</script>

</body>
</html>