原理:
用户点击获取验证码时,发送手机号到后端接口,后端接受请求后,将手机号以及验证码发给短信网关,并将手机号和短信验证码保存起来。用户收到短信后,输入验证码,然后前端将验证码和手机号传给后端,后端校验手机号和验证码是否与之前保存的一致,如果一致,则验证通过,向前端发送认证状态,认证通过的状态下前端进行页面的跳转或者是其他的业务逻辑。
代码:
html代码
<div class="box">
<div class="center" style="padding-top:0.8rem;">
<ul>
<li class="clearfix">
<input type="number" class="sjh" placeholder="手机号" id="phonenum2" style="color:#535353;"/>
<button class="fyzm" id="embed-submit">发送验证码</button>
</li>
<li>
<input type="number" class="yzm" placeholder="验证码" id="vernum" style="color:#535353;"/>
</li>
</ul>
</div>
<div class="bottom">
<button class="btn" id="submit" href="javascript:">提交</button>
</div>
</div>
js代码
//点击发送验证码
$("#embed-submit").unbind(\'click\').bind(\'click\',function(){
$("#vernum").val("");
var tel = $("#phonenum2").val();
var reg = /^0?1[3|4|5|7|8][0-9]\d{8}$/;
if (reg.test(tel)) {//验证手机号码
yzget_fn();
}else{
alert_(\'请输入有效电话号码\');
}
});
//发送手机号到后端接口
function yzget_fn(){
$("#embed-submit").attr(\'disabled\',\'disabled\');
$("#embed-submit").addClass("fyzmOn"); //发送验证码按钮样式变化
//获取验证码
var phonenum = $("#phonenum2").val();//电话号码
$.ajax({
url:"",
type: "get",
dataType: "json",
success:function(msg){
if(msg.message==\'success\'){
var second = msg.term; //秒数
var embedSubmit = $("#embed-submit");
var i = parseInt(second*1)+1;
var time_ = setInterval(function(){
if(i>0){
i--;
embedSubmit.html("正在获取"+i);
}else{
clearInterval(time_);
$("#embed-submit").attr(\'disabled\',false);
$("#embed-submit").removeClass("fyzmOn");
embedSubmit.html(\'发送验证码\');
}
},1000)
}else if(msg.message==\'error\'){
alert_(msg.data);
$("#embed-submit").attr(\'disabled\',false);
$("#embed-submit").removeClass("fyzmOn");
}
}
})
}
//提交验证信息,点击提交把手机号和验证码传给后端
$(\'#submit\').unbind(\'click\').bind(\'click\',function(){
var self_=$(this);
if(self_.attr("odisabled")=="odisabled"){
$(".buyFrame").css("display","block");
alert_("操作过于频繁,请5秒之后重试");
var timeable = setTimeout(function(){
self_.attr(\'odisabled\',false);
clearTimeout(timeable);
},5000)
}else{
var vernum = $("#vernum").val(); //验证码
var phonenum = $("#phonenum2").val();//电话号码
var reg = /^0?1[3|4|5|7|8][0-9]\d{8}$/;
if (!reg.test(phonenum)) {//验证手机号码
alert_("请先输入有效电话号码");
return false
}else if(!vernum){
alert_(\'请输入验证码\');
return false;
}else{
$.ajax({
//获取id,challenge,success(是否启用failback)
url: "https://www.*******/dealwine/sendsmsverify?mobile="+phonenum+"&wxopenid=${wxopenid}"+"&smscode="+vernum,
type: "post",
dataType: "json",
success: function (data) {
if(data.message==\'success\'){
alert_(\'验证成功\');
$("#phonenum2").val($("#phonenum").val());
self_.attr(\'odisabled\',\'odisabled\');
var returnurl = "${returnurl}";
history.go(-1);
}else{
alert_(\'验证失败\');
self_.attr(\'odisabled\',\'odisabled\');
}
$("#submit").attr(\'disabled\',false);
},error:function(){
alert_(\'信息出错,请重新尝试!\');
$("#submit").attr(\'disabled\',false);
self_.attr(\'odisabled\',\'odisabled\');
}
})
}
}
});