testAjax.jsp :
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
function ajax(){
var xhr=getXhr();
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
if(xhr.status==200){
document.getElementById("resText").innerHTML=xhr.responseText;
}
}
}
xhr.open('get','test',true);
xhr.send(null);
}
function getXhr(){
var xhr=null;
if(window.ActiveXObject){
xhr=new ActiveXObject("Microsoft.XMLHTTP");
}else if(window.XMLHttpRequest){
xhr=new XMLHttpRequest();
}
return xhr;
}
</script>
</head>
<body>
<input type="button" value="以ajax方式获取数据" onclick="ajax();">
<div id="resText"></div>
</body>
</html>
TestServlet.java :
public class TestServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter pw=response.getWriter();
pw.print("hello ajax...");
pw.close();
}
}
为Servlet映射的url为test。
点击按钮后:
如果get方式要传递参数,可以这样:
xhr.open('get','test?name=tom&age=23',true);
public class TestServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name=request.getParameter("name");
String age=request.getParameter("age");
PrintWriter pw=response.getWriter();
pw.print("name:"+name+" ,age:"+age);
pw.close();
}
}