<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ajax</title>
<script>
function fn1(){
// 1创建ajax引擎对象-----》所有的信息都是通过ajax引擎传递
var xmlhttp=new XMLHttpRequest();
//2 绑定监听
xmlhttp.onreadystatechange=function(){
//5 接受响应的数据
var ret = xmlhttp.responseText;
if(xmlhttp.readyState==4&&xmlhttp.status==200){
//alert(ret);
document.getElementById("span1").innerHTML=ret;
}
}
//3 绑定地址
xmlhttp.open("GET","/day49/ajaxServlet",true);
//4 发送请求
xmlhttp.send();
}
function fn2(){
// 1创建ajax引擎对象-----》所有的信息都是通过ajax引擎传递
var xmlhttp=new XMLHttpRequest();
//2 绑定监听
xmlhttp.onreadystatechange=function(){
//5 接受响应的数据
var ret = xmlhttp.responseText;
if(xmlhttp.readyState==4&&xmlhttp.status==200){
//alert(ret);
document.getElementById("span2").innerHTML=ret;
}
}
//3 绑定地址
xmlhttp.open("GET","/day49/ajaxServlet",false);
//4 发送请求
xmlhttp.send();
}
</script>
</head>
<body>
<input type="button" value="异步访问服务器" onclick="fn1()"><span id="span1"></span>
<input type="button" value="同步访问服务器" onclick="fn2()"><span id="span2"></span>
<input type="button" value="测试按钮" onclick=alert("看我")>
</body>
</html>
对应的servlet
package cn.lijun.demo;
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 {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//response.getWriter().write("qiang");
//request.getParameter("");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response.getWriter().write(Math.random()+"");
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}