<%@pagelanguage="java"contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPEhtmlPUBLIC"-//W3C//DTDHTML4.01Transitional//EN""http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <Metahttp-equiv="Content-Type"content="text/html;charset=UTF-8"> <title></title> <scripttype="text/javascript"src="${pageContext.request.contextPath}/js/jquery-1.11.1.min.js"></script> <scripttype="text/javascript"> $(function(){ $(":input[name='username']").change(function(){ varval=$(this).val(); val=$.trim(val); if(val!=""){ varurl="${pageContext.request.contextPath}/validatUsername"; varargs={"username":val,"time":newDate()}; $.post(url,args,function(data){ $("#message").html(data); }); } }); }) </script> </head> <body> <!-- 1.导入JQuery库 2.获取name="username"的结点:username 3.1为username添加change响应函数。去除空格且不为空。准备发生Ajax请求。 3.2发送Ajax请求检验username是否可用 3.3在服务端返回一个html片段 3.4在客户端浏览器把其直接添加到#message的html中 --> <formaction=""method="post"> Username<inputtype="text"name="username"/><br/> <divid="message"></div><br/> <inputtype="submit"value="submit"/> </form> </body> </html>
servlet
protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{ //TODOAuto-generatedmethodstub List<String>usernames=Arrays.asList("aaa","bbb","ccc"); Stringusername=request.getParameter("username"); Stringresult=null; if(usernames.contains(username)){ result="<fontcolor='red'>该用户名已经被使用</font>"; }else{ result="<fontcolor='red'>该用户名可以使用</font>"; } response.setContentType("text/html;charset=UTF-8"); response.setCharacterEncoding("UTF-8"); response.getWriter().print(result); }
本文出自 “优赛工作室” 博客,请务必保留此出处http://www.jb51.cc/article/p-rogobamf-qg.html
原文链接:https://www.f2er.com/ajax/162443.html