前端页面:
<!--验证码输入框 --> <input type="text" class="entry" value="" placeholder="请输入短信验证码" id="u_code" autocomplete="off"> <!--获取验证码的按钮 --> <input type="button" id="smsBtn" class="obtain" value="获取验证码" onclick="getRandNum(this);"> <!-- 服务器返回的验证码隐藏域 --> <input type="hidden" name="randNum" id="randNum" value="" /> <a class="land" onclick="safeLogin()">确认登陆</a>
JS发送AJAX请求发送验证码:
获取到服务器响应后更新页面的隐藏域,在用户提交表单的时候可以此判断验证码是否输入正确。
1 <script> 2 var wait=0; 3 4 function getRandNum(){ 5 var photo = "${safePhone }"; 6 var auId = "${auId }" ; 7 //alert(photo); 8 var xmlHttp = null; 9 //表示当前浏览器不是ie,如ns,firefox 10 if(window.XMLHttpRequest) { 11 xmlHttp = new XMLHttpRequest(); 12 } else if(window.ActiveXObject) { 13 xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); 14 } 15 xmlHttp.onreadystatechange=function() 16 { 17 if (xmlHttp.readyState==4 && xmlHttp.status==200) 18 { 19 alert("验证码发送成功,请注意查收"); 20 document.getElementById("randNum").value=xmlHttp.responseText; 21 wait=60; 22 var smsBtn = document.getElementById("smsBtn"); 23 time(smsBtn); 24 } 25 } 26 xmlHttp.open("GET","${basePath }login/sendSmsCode.action?phone="+photo+"&auId="+auId,true); 27 xmlHttp.send(); 28 29 } 30 31 //计时 32 function time(o) { 33 if (wait == 0) { 34 o.removeAttribute("disabled"); 35 //o.setAttribute("disabled", false); 36 o.value="获取验证码"; 37 wait = 60; 38 document.getElementById("randNum").value=""; 39 } else { 40 o.setAttribute("disabled", true); 41 o.value="已发(" + wait + "s)"; 42 wait--; 43 setTimeout(function() {time(o)},1000); 44 } 45 } 46 47 function safeLogin(){ 48 var u_code = document.getElementById("u_code").value; 49 var s_code = document.getElementById("randNum").value; 50 //alert(u_code); 51 if(u_code==""){ 52 alert("验证码不能为空!"); 53 return false ; 54 } 55 if(u_code!=s_code){ 56 alert("验证码输入不正确,请输入正确验证码!"); 57 return false ; 58 } 59 60 var safeLoginFrm = document.getElementById("safeLoginFrm"); 61 safeLoginFrm.submit(); 62 } 63 64 </script>
服务器端ACTION:
1 /* 2 * 发送短信验证码 3 */ 4 public void sendSmsCode() { 5 HttpServletResponse response = ServletActionContext.getResponse(); 6 7 // 产生6位随机数字 8 Random r = new Random(); 9 String randNum = ""; 10 for (int i = 0; i < 6; i++) { 11 randNum += r.nextInt(10); 12 } 13 String content = "【验证码】" + randNum + "(后台安全登陆验证码,一分钟内有效)"; 14 // 发送短信begin: 15 Map<String, String> sendMap = SendSmsMessage 16 .sendMessage(content, phone); 17 Integer sms_code = Integer.parseInt(sendMap.get("Code")); 18 String sms_result = sendMap.get("Result"); 19 // 发送短信end 20 21 try { 22 PrintWriter writer = response.getWriter(); 23 writer.print(randNum); 24 writer.flush(); 25 writer.close(); 26 } catch (Exception e) { 27 e.printStackTrace(); 28 } 29 30 }
上面简单实现了验证码功能,也算是一个AJAX的一个实例。