Ajax典型应用——验证用户名是否可用
发布时间:2020-12-16 00:29:59 所属栏目:百科 来源:网络整理
导读:步骤: !-- 1.导入jQuery包 2:获取 name="username"的节点,为该节点添加change()相应函数 3:获取username的属性值,去处前后空格,当不为空的时候,准备发送ajax请求 4:发送ajax请求,url为servlet,agrs为传递的json参数,该参数是像servlet中传递的,
步骤: <!-- 2:获取 name="username"的节点,为该节点添加change()相应函数
<%@ page language="java" pageEncoding="UTF-8"%> <html:html lang="true"> <head> <!--${pageContext.request.contextPath}获取该项目的绝对路径 --> <script type="text/javascript" src="${pageContext.request.contextPath}/scripts/jquery-1.7.2.js"></script> <script type="text/javascript"> $(function(){ $(":input[name='username']").change(function(){ var val=$(this).val(); //获取username节点中的value属性值 val=$.trim(val); //取出前后空格 if(val!=""){ var url="${pageContext.request.contextPath}/valiateUserName"; var agrs={"userNamesyq":val,"time":new Date()}; //准备传递的参数,注意该参数的类型设置为json格式的 $.post(url,agrs,function(data){ $("#message").html(data); //设置id="message"中的内容为data }); } }); }); </script> </head> <body> <form action="" method="post"> UserName: <input type="text" name="username" /> <br> <br> <div id="message"></div> <br> <input type="submit" value="Submit" /> </form> </body> </html:html> servlet中检验用户名是否正确,并发送一个html片段给ajax public class ValiateUserName extends HttpServlet { public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { } public void doPost(HttpServletRequest request,IOException { List<String> list=Arrays.asList("aaa","bbb","ccc"); String userName=request.getParameter("userNamesyq"); //获取从ajax中传来的属性值,该数据是从ajax中的json中传来的 System.out.println(userName+"**********"); String result=null; if(list.contains(userName)){ result="<font color='red'>该用户名已经被使用</font>"; }else{ result="<font color='green'>该用户名可以使用</font>"; } response.setCharacterEncoding("UTF-8"); //解决中文乱码现象 response.setContentType("text/html"); //设置传回数据的类型 response.getWriter().print(result); //传回html数据 } }实际上对用户名的检验要从数据库打交道,本程序只是讲解ajax检验用户名是否可用的原理。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |