日期:2014-05-16  浏览次数:20791 次

分享ajax的一个小例子(代码)
ajax.jsp代码
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <title> New Document </title>
  <script type="text/javascript">
  <!--

    var xmlHttpReuquest = null;//声明一个空对象以接受XMLHttpRequest对象
var ajaxSubmit = function()
{
if(window.ActiveXObject)//IE
{
xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest)//Other Brownser
{
xmlHttpRequest = new XMLHttpRequest();
}
if(null != xmlHttpRequest)
{
var value1 = document.getElementById("v1").value;
var value2 = document.getElementById("v2").value;
// 准备发送
//xmlHttpRequest.open("GET","AjaxServlet?num1="+value1+"&num2="+value2,true);
// 状态改变
//xmlHttpRequest.onreadystatechange = ajaxCallBack;
// 发送
//xmlHttpRequest.send(null);//如果是通过get传递的就填null或者不填。

xmlHttpRequest.open("POST","AjaxServlet",true);
xmlHttpRequest.onreadystatechange = ajaxCallBack;
xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlHttpRequest.send("num1="+value1+"&num2="+value2);

}
}


function ajaxCallBack()
{
//alert("hello");//执行的时候会调用4次。
          //这里可以参考此博客http://201303272244.iteye.com/admin/blogs/1839944
if(xmlHttpRequest.readyState == 4)
{
if(xmlHttpRequest.status == 200)
{
var responseText =xmlHttpRequest.responseText;
document.getElementById("divt").innerHTML = responseText;
}
}
}
  //-->
  </script>
</head>
<body>
<input type="submit" value="click this button" onclick="ajaxSubmit();">
<input type="text" id="v1" name="num1">
<input type="text" id="v2" name="num2">
<div id="divt" class="">
</div>
</body>
</html>

AjaxServlet.java

public class AjaxServlet extends HttpServlet
{
protected void doGet(HttpServletRequest req,HttpServletResponse resp)
throws ServletException,IOException
{
PrintWriter out = resp.getWriter();

System.out.println("get or post invoked");
resp.setHeader("pragma","no-cache");
resp.setHeader("cache-control","no-cache");//无缓存

String value1 = req.getParameter("num1");
String value2 = req.getParameter("num2");

String value3 = String.valueOf(Interger.valueOf(value1)+Interger.valueOf(value2));
try
{
Thread.sleep(3000);//延迟3s
}
catch (InterruptedException e)
{
e.printStackTrace();
}
out.println(value3);
out.flush();
}

protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException,IOException
{
this.doGet(req,resp);
}
}