一.创建servlet类
doGet中的方法
PrintWriter out = response.getWriter();
out.println("hello world ,this is my first ajax");
out.flush();
二.编写页面jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<script type="text/javascript">
window.onload = function()
{
var myAjaxButton = document.getElementById("ajaxButton");
myAjaxButton.onclick = function()
{
//声明一个空对象,用来接收XMLHttpRequest
var xmlHttpRequest = null;
if(window.ActiveXObject)//IE
{
xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest)
{
xmlHttpRequest = new XMLHttpRequest();
}
if(null != xmlHttpRequest)
{
//准备建立一个连接
xmlHttpRequest.open("GET","MyAjaxServlet",true);
//关联ajax的回调函数
xmlHttpRequest.onreadystatechange = function()
{
if(xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200)
{
//处理响应
document.getElementById("ajaxDiv").innerHTML = xmlHttpRequest.responseText;
}
}
//真正向客户端发送数据
xmlHttpRequest.send(null);
}
}
}
</script>
</head>
<body>
<form action="AjaxServlet" method="post">
<input type="button" value="get info from server" id="ajaxButton">
<div id="ajaxDiv"></div>
</form>
</body>
</html>