Ajax发送验证码实例


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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值