分享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" οnclick="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);
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值