import java.io.IOException; import java.io.PrintWriter; import java.net.URLDecoder; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class AjaxServer extends HttpServlet { protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException { doGet(httpServletRequest, httpServletResponse); } protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException { try{ httpServletResponse.setContentType("text/html;charset=utf-8"); PrintWriter out = httpServletResponse.getWriter(); //inte用来记录验证次数 Integer inte = (Integer) httpServletRequest.getSession().getAttribute("total"); int temp = 0; if (inte == null) { temp = 1; } else { temp = inte.intValue() + 1; } httpServletRequest.getSession().setAttribute("total",temp); //1.取参数 String old = httpServletRequest.getParameter("name"); //String name = new String(old.getBytes("iso8859-1"),"UTF-8"); String name = URLDecoder.decode(old,"UTF-8"); System.out.println(old+" oooooooooooooooooo"); //2.检查参数是否有问题 if(old == null || old.length() == 0){ out.println("用户名不能为空"); } else{ if(name.equals("hpu")){ //4。和传统应用不同之处。这一步需要将用户感兴趣的数据返回给页面段,而不是将一个新的页面发送给用户 //写法没有变化,本质发生了改变 out.println("用户名[" + name + "]已经存在,请使用其他用户名, " + temp); } else{ out.println("用户名[" + name + "]尚未存在,可以使用该用户名注册, " + temp); } } } catch(Exception e){ e.printStackTrace(); } } }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>用户校验ajax实例</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript" src="js/jquery-1.8.0.js"></script> <script type="text/javascript" src="js/verify.js"></script> </head> <body> <h1> 用户校验ajax实例</h1><br> 请输入用户名:<br/> <!-- ajax不需要使用表单进行数据提交,因此不用写表单标签 --> <!-- ajax不需要name属性,只需要一个id的属性 --> <input type="text" id="username"/> <input type="button" value="校验" onclick="verify()"/> <!-- 这个div用于存放服务器返回的信息,开始为空 --> <!-- id属性定义是为了利用dom的方式找到某一个节点,进行操作 --> <div id="result"> </div> </body> </html>
function verify(){ var jqueryObj=$("#username"); var userName=jqueryObj.val(); $.get("AjaxServer?name="+userName,null,callback); } function callback(data){ var resultObj=$("#result"); resultObj.html(data); }
function verify(){ var jqueryObj=$("#username"); var userName=jqueryObj.val(); $.get("AjaxServer?name="+userName,null,callback); } function callback(data){ var resultObj=$("#result"); resultObj.html(data); } //给URL加一个时间戳,骗过浏览器,不读取缓存 function convertURL(url){ //获取时间戳 var timstamp=(new Date()).valueOf(); //将时间戳信息拼接到url上 if(url.indexOf("?")>0){ url=url+"&t="+timstamp; }else{ url=url+"?t="+timstamp; } return url; }
这样,就可以保证每次发出的url请求地址与上次不一样,让浏览器不去使用缓存来达到我们的效果
转载请注明出处:http://blog.csdn.net/acmman/article/details/47755539