日期:2014-05-16 浏览次数:20668 次
JSP页面内容: <td align="right" class="bg_table02" > <font color="red">*</font>手机: </td> <td class="bg_table02"> <html:text property="subMobile" size="20" styleClass="input" /> <input class=button01 name="captchaBtn" type="button" value="获取验证码" onclick="getCaptcha()" /> </td> JSP页面中的javascript代码: var xmlhttp; function operurl(){ if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); } else { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } } function getCaptcha(){ if(isNumber(document.forms(0).subMobile.value)){ operurl(); xmlhttp.open("get","<%=request.getContextPath()%>/qualityOpinionCas.cas?functionCode=getCaptcha&subMobile="+document.forms(0).subMobile.value); xmlhttp.onreadystatechange= function (){ if(xmlhttp.readyState==4){ if(xmlhttp.status==200){ var res=xmlhttp.responseText; if(res!=""){ document.forms(0).rcaptcha.value=res; //按钮灰10秒 document.forms(0).captchaBtn.disabled=true; setTimeout("document.forms(0).captchaBtn.disabled=false;",10000); return; } } } }; xmlhttp.send(); } } Action中代码: /** * 获取验证码 */ private ActionForward getCaptcha(BActionContext context) throws BsiException { HttpServletRequest request = context.getRequest(); HttpServletResponse response = context.getResponse(); String subMobile = request.getParameter("subMobile"); String captcha = get5Radom();//获取随机生成5位随机数 String content = ""; if (null != subMobile) { String message = "您好,欢迎使用Ajax技术,验证码为:"+ captcha + "。您有任何疑问,欢迎拨打热线进行咨询"; try { CpfzUtil.SMSExceues(subMobile, message); //调用一个接口,用于发送短信 content = captcha; } catch (Exception e) { e.printStackTrace(); } } try { request.setCharacterEncoding("gbk"); response.setContentType("text/xml;charset=gbk"); } catch (UnsupportedEncodingException el) { el.printStackTrace(); } PrintWriter out; try { out = response.getWriter(); out.print(content); out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } return null; } // 随机生成5位随机数 private String get5Radom() { String newString = null; // 得到0.0到1.0之间的数字,并扩大100000倍 double doubleP = Math.random() * 100000; // 如果数据等于100000,则减少1 if (doubleP >= 100000) { doubleP = 99999; } // 然后把这个数字转化为不包含小数点的整数 int tempString = (int) Math.ceil(doubleP); // 转化为字符串 newString = "" + tempString; // 把得到的数增加为固定长度,为5位 while (newString.length() < 5) { newString = "0" + newString; } return newString; }