源码:
http://download.csdn.net/detail/m1872216/4651239
Ajax的局部刷新:
input.jsp
<body>
<div id="msg" style="color:red"></div>
<form action="login.do" method="post" name="form1" οnsubmit="return onClick()">
<table border="1">
<tr>
<td>
设置数字:
</td>
<td>
<input type="text" name="num"/>
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="提交"/>
</td>
</tr>
</table>
</form>
<script type="text/javascript" src="js/myAjax.js"></script>
<script type="text/javascript">
function onClick(){
var num=document.form1.num.value;
var params="num="+num;
ajaxPost("login.do",params,function(txt){
document.getElementById("msg").innerHTML=txt;
});
return false;
}
</script>
</body>
servlet:
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
//String count=request.getParameter("count");
response.setContentType("text/html;charset=utf-8");
HttpSession session=request.getSession();
//访问的次数
if(session.getAttribute("times")==null){
Random rd=new Random();
int count=rd.nextInt(10);
System.out.println(count);
session.setAttribute("count", count);
session.setAttribute("times", 0);
}
///
if((Integer)session.getAttribute("times")==0){
int times=(Integer)session.getAttribute("times");
session.setAttribute("times", times+1);//初次访问
showResult(request,response);
}else{
showResult(request,response);
}
}
public void showResult(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out=response.getWriter();
HttpSession session=request.getSession();
//获取访问的第几次
int times=(Integer)session.getAttribute("times");
//获取客户端提交的数据
int num=0;
try{
num=Integer.parseInt(request.getParameter("num"));
}catch(NumberFormatException ne){
out.println("非法输入");
return;
}
//获取随机数
int realnum=(Integer)session.getAttribute("count");
if(num>realnum){
out.println("再小一点");
session.setAttribute("times", times+1);
}else if(num<realnum){
out.println("再大一点");
session.setAttribute("times", times+1);
}else{
times=(Integer)session.getAttribute("times");
out.println("答对了,花了"+times+"次");
session.removeAttribute("times");
}
}