代码实现
1. 客户端实现
1.1. 创建XMLHttpRequest 对象
XMLHttpRequest
对象用于同幕后服务器交换数据。这意味着可以更新网页的部分,而不需要重新加载整个页面。
所有现代浏览器(Chrom、IE7+、Firefox、Safari 以及 Opera)都有内建的 XMLHttpRequest
对象。
variable = new XMLHttpRequest();
老版本的 Internet Explorer(IE5 和 IE6)使用 ActiveX 对象:
variable = new ActiveXObject("Microsoft.XMLHTTP");
综上所述, XMLHttpRequest
对象的语法是:
var xhttp;
if (window.XMLHttpRequest) {
// 用于现代浏览器的代码
xhttp = new XMLHttpRequest();
} else {
// 用于现代浏览器的代码
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
1.2向服务器发送请求
如需向服务器发送请求,我们使用 XMLHttpRequest 对象的 open() 和 send() 方法:
//GET请求
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
//POST请求
xhttp.open("POST", "ajax_test.asp", true);
xhttp.send("fname=Bill&lname=Gates");//请求体
1.3获取服务器的响应结果
readyState 属性存留 XMLHttpRequest 的状态。
onreadystatechange 属性定义当 readyState 发生变化时执行的函数。
status 属性和 statusText 属性存有 XMLHttpRequest 对象的状态。
每当 readyState 发生变化时就会调用 onreadystatechange 函数。
当 readyState 为 4,status 为 200 时,响应就绪:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
完整代码如下
<!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-demo/ajaxServlet");
xhttp.send();
//3. 获取响应
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
}
};
</script>
</body>
</html>
2. 服务端实现
@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);
}
}
响应结果: