前台页面:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'ajax.jsp' starting page</title>
<script type="text/javascript">
function testAjax() {
//创建AJAX对象
var request = null;
//根据浏览器的不同使用不同的创建方式
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
} else if (window.ActiveXObject) {
request = new ActiveXObject("Msxml2.XMLHTTP");
} else {
console.log("找不到指定的创建方式[" + window.navigator.userAgent + "]");
}
//初始化对象
//request.open(method, url, async, username, password)
request.open("post", "hi.action", true);
//接受响应数据
request.onreadystatechange = function() {
//0-4
if (request.readyState == 4) {
//监听状态码
if (request.status == 200) {
alert(request.responseText);
}
}
}
//发送请求
request.send(null);
//同步异步
//alert("证明是同步还是异步");
};
</script>
</head>
<body>
<h1>AJAX简单入门<%=Math.random()%></h1>
<input type="button" value="testAjax" onclick="testAjax();">
<hr />
<h3>XMLHttpRequest就是我们说的AJAX对象</h3>
<h3>AJAX的属性</h3>
<ol>
<li>readyState:ajax的状态码 <pre>
0 - (未初始化)还没有调用send()方法
1 - (载入)已调用send()方法,正在发送请求
2 - (载入完成)send()方法执行完成,已经接收到全部响应内容
3 - (交互)正在解析响应内容
4 - (完成)响应内容解析完成,可以在客户端调用了
</pre>
</li>
<li>status:http协议的状态码</li>
<li>responseText:服务器返回的文本内容</li>
<li>responseXML:服务器返回的XML格式的数据</li>
</ol>
<h3>AJAX的方法</h3>
<ol>
<li>open:初始化
<ol>
<li>初始化ajax对象(请求方式,资源路径,同步或者异步)</li>
<li>默认为异步请求(true),如果设置为false则为同步</li>
</ol>
</li>
<li>send:发送请求</li>
</ol>
<h3>AJAX的事件</h3>
<ol>
<li>onreadystatechange:
<ol>
<li>当状态码改变的时候触发这个事件</li>
</ol>
</li>
</ol>
</body>
</html>
后台:
package com.zhaoran.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/hi.action")
public class HiServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
System.out.println(req.getHeader("User-Agent")+Math.random());
System.out.println(req.getAttribute("uname"));
System.out.println(req.getAttribute("realname"));
resp.getWriter().print("ajax-back"+Math.random());
}
}