微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Ajax实现异步验证用户是否存在

在Index.jsp页面中 //使用ajax进行异步校验,校验登录名在数据库是否存在 //创建ajax引擎 function createXmlHttpRequest(){ var xmlHttp; try{ //Firefox,Opera 8.0+,Safari xmlHttp=new XMLHttpRequest(); }catch (e){ try{ //Internet Explorer xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); }catch (e){ try{ xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); }catch (e){} } } return xmlHttp; } function checklogonName(){ var logonName = document.getElementById("logonName").value; //第一步:创建ajax引擎 var xmlHttp = createXmlHttpRequest(); //第二步:事件处理函数,实质上相当一个监听,监听服务器与客户端的连接状态 xmlHttp.onreadystatechange = function(){ if(xmlHttp.readyState==4){ if(xmlHttp.status==200){ var data = xmlHttp.responseText; //alert(data); if(data==1){ alert("当前输入的登录名["+logonName+"]已被其他人占用,请重重新输入!"); document.getElementById("logonName").value = ""; document.getElementById("logonName").focus(); } } } } //第三步:与后台服务器建立一个连接 xmlHttp.open("post","../../checklogonName",true); xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); //第四步:发送请求的参数 xmlHttp.send("logonName="+logonName); } 在servlet页面中: IElecUserService elecUserService = (IElecUserService) ServiceProvider.getService(IElecUserService.SERVICE_NAME); public void doPost(HttpServletRequest request,HttpServletResponse response) throws servletexception,IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); String logonName = request.getParameter("logonName"); /** * checkflag:判断当前登录名在数据库中是否存在的标识 * checkflag=1:如果值为1,说明当前登录名在数据库中有重复记录,则不能进行保存 * checkflag=2:如果值为2,说明当前登录名在数据库中没有重复值,可以进行保存 */ String checkflag = elecUserService.checklogonName(logonName); out.print(checkflag); out.flush(); out.close(); }

原文地址:https://www.jb51.cc/ajax/165942.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐