验证码倒计时--- jQery实现
场景用在实现获取手机验证码:jQuery实现倒计时获取验证码
$('#dyMobileButton').click(function () {
var time=10;
var phone=$('#phone').val();
//验证手机号不能为空
if (phone.length==0){
$('#a').html('<b>手机号不能为空</b>').css('color','red');
return false;
}else {
$('#a').html('').css('color','red');
}
var timers=setInterval(function () {
time--;
//判断验证码倒计时
if (time>0){
//验证码倒计时大于0按钮无法点击 出现倒计时时间
$('#dyMobileButton').html(time+'秒');
$('#dyMobileButton').prop('disabled');
}else {
//验证码时间过期按钮正常点击
$('#dyMobileButton').html('发送验证码');
$('#dyMobileButton').prop('disabled',false);
clearInterval(timers);
}
},1000)
$.ajax({
type: "POST",
url: "{:url('Login/sendCode')}",
data: {phone:phone},
success: function(msg){
if (msg.code==500){
$('#a').html(msg.msg);
}
}
});
})
接口回调:
$phone=input('phone'); // 验证参数 if(!preg_match('/^1[3-9]\d{9}$/',$phone)){ return json(['code'=>500,'msg'=>'手机号有误','data'=>null]); } //生成随机的验证码 $read=rand(1,9999); $tod=cache('PYGU_ti_'.$phone); if (!empty($tod)){ return json(['code'=>500,'msg'=>'一分钟只能发送一次','data'=>null]); } $content = "【品优购】你的验证码是:{$read},3分钟内有效!"; $data=sendmsg($phone,$content); if ($data){ $lot= date('Y-m-d:H:i:s',time()); cache('PYGU_ti_'.$phone,$lot,60); //验证成功将验证码存储到cache中 cache('PYGU_'.$phone,$read,60); return json(['code'=>200,'msg'=>'验证码发送成功','data'=>$read]); }else{ return json(['code'=>500,'msg'=>'验证码发送失败','data'=>['phone'=>$phone]]); } }

浙公网安备 33010602011771号