1 Ajax简介
1 ajax概念
![](https://images2017.cnblogs.com/blog/1320077/201801/1320077-20180126114134928-1489515010.png)
2 什么是同步?什么是异步?
![](https://images2017.cnblogs.com/blog/1320077/201801/1320077-20180126114215115-1084851212.png)
3 ajax原理
![](https://images2017.cnblogs.com/blog/1320077/201801/1320077-20180126114251303-2013734453.png)
2 JavaScript原生的ajax
![](https://images2017.cnblogs.com/blog/1320077/201801/1320077-20180126114400506-964832868.png)
![](https://images2017.cnblogs.com/blog/1320077/201801/1320077-20180126114620694-775804334.png)
![](https://images2017.cnblogs.com/blog/1320077/201801/1320077-20180126114705287-149803467.png)
1 ajax.html代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
function fn1(){
//1、创建ajax引擎对象 ---- 所有的操作都是通过引擎对象
var xmlHttp = new XMLHttpRequest();
//2、绑定监听 ---- 监听服务器是否已经返回相应数据
xmlHttp.onreadystatechange = function(){
if(xmlHttp.readyState==4&&xmlHttp.status==200){
//5、接受相应数据
var res = xmlHttp.responseText;
document.getElementById("span1").innerHTML = res;
}
}
//3、绑定地址
xmlHttp.open("GET","/WEB22/ajaxServlet?name=lisi",true);
//4、发送请求
xmlHttp.send();
}
function fn2(){
//1、创建ajax引擎对象 ---- 所有的操作都是通过引擎对象
var xmlHttp = new XMLHttpRequest();
//2、绑定监听 ---- 监听服务器是否已经返回相应数据
xmlHttp.onreadystatechange = function(){
if(xmlHttp.readyState==4&&xmlHttp.status==200){
//5、接受相应数据
var res = xmlHttp.responseText;
document.getElementById("span2").innerHTML = res;
}
}
//3、绑定地址
xmlHttp.open("POST","/WEB22/ajaxServlet",false);
//4、发送请求
xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlHttp.send("name=wangwu");
}
</script>
</head>
<body>
<input type="button" value="异步访问服务器端" onclick="fn1()"><span id="span1"></span>
<br>
<input type="button" value="同步访问服务器端" onclick="fn2()"><span id="span2"></span>
<br>
<input type="button" value="测试按钮" onclick="alert()">
</body>
</html>
2 AjaxServlet代码
package www.test.ajax01;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class AjaxServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//response.getWriter().write("zhangsan");
/*try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}*/
String parameter = request.getParameter("name");
response.getWriter().write(Math.random()+parameter);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
3 注意事项
![](https://images2017.cnblogs.com/blog/1320077/201801/1320077-20180126134719865-963068187.png)
![](https://images2017.cnblogs.com/blog/1320077/201801/1320077-20180126134739381-1153151525.png)
4 ajax图解
![](https://images2017.cnblogs.com/blog/1320077/201801/1320077-20180126134808022-92688401.png)