示例:发送手机验证码
防止页面刷新后,发送验证码按钮重置
注:橙色部分为后增加代码,为防止验证码等待期间用户退出或者切换到其他页面以至于很久之后回到当前页面倒计时还在的问题,加入时间对比,记录用户发送验证码时+60秒后的时间,下次进入判断当前时间是否大于记录时间,如果大于或者不存在,则距离上次发送验证码已超过60秒,这时不再读取倒计时。
1.将发送验证码放入cookie
$.cookie("time", time);
2.当页面载入时判断cookie是否为空
var date = $.cookie("date");//取上次发送验证码时记录的时间 (发送时间+60s)
if(date && (new Date().getTime() < new Date(date).getTime()) ){//判断当前时间是否小于记录时间
if ($.cookie("time") != undefined && $.cookie("time") != 'NaN'
&& $.cookie("time") != 'null') {// cookie存在倒计时
timekeeping();//修改发送验证码按钮方法
} else {// cookie 没有倒计时
$('#ihd_getcode_btn').prop("disabled", false);
_button.removeClass("disabled");
}
}
3.时间未到时进入修改发送验证码按钮方法
function timekeeping() {
// 把按钮设置为不可以点击
_button.prop("disabled", true);
_button.addClass("disabled");
// 从cookie 中读取剩余倒计时
var time = $.cookie("time");
var interval = setInterval(function() {// 每秒读取一次cookie
// 把剩余总倒计时减掉1
time--;
if (time > 0) {// 剩余倒计时不为零
// 在发送按钮显示剩余倒计时
_button.html(time + "秒后重发");
// 重新写入总倒计时
$.cookie("time", time,{ path: '/',expires : (1/86400)*time});
} else {// 剩余倒计时为零,则显示 重新发送,可点击
// 清除定时器
clearInterval(interval);
// 删除cookie
time = $.cookie("time", time, {expires : -1});
_button.prop("disabled", false);
_button.removeClass("disabled");
_button.html("获取验证码");
}
}, 1000);
};
注:发送验证码方法:
$(".ihd_getcode_btn").click(function() {
var phone = $('input[name="phone"]').val();
if (!mobileRegex.test(phone)) {
apus.ui.toastr.error("手机号格式错误");
return;
}
// 发送验证码
_button.prop("disabled", true);
_button.addClass("disabled");
apus.ui.maskLlock(true);
$.ajax({
type : "post",
url : getUrl('/vip/sendCode'),
dataType : "json",
data : {
phone : phone
},
success : function(result) {
apus.ui.maskLlock(false);
if (result.success) {
apus.ui.toastr.info("验证码发送成功");
$.cookie("time", 60,{ path: '/',expires : (1/86400)*60});
var curDate = new Date();
curDate.setSeconds(curDate.getSeconds()+60);
$.cookie("date",curDate,{ path: '/',expires : (1/86400)*60});
timekeeping();
} else {
apus.ui.toastr.error("验证码发送失败," + result.msg);
_button.prop("disabled", false);
_button.removeClass("disabled");
_button.html("获取验证码");
}
},
error : function(e) {
apus.ui.maskLlock(false);
_button.prop("disabled", false);
_button.removeClass("disabled");
_button.html("获取验证码");
apus.ui.toastr.error("网络异常,请稍候重试");
}
});
});