点击发送验证码,按钮进入60s倒计时,用cookie记录60s。
//发送验证码 function sendCode(obj){ var phone = $("#phone").val(); var result = isPhoneNum(); if(result){ doPostBack(‘?member/sendsms/‘,backFunc1,{"phone":phone}); addCookie("secondsremained",60,60);//添加cookie记录,有效时间60s settime(obj);//开始倒计时 } } // 创建cookie var addCookie = function (name, value, time) { let d = new Date(); d.setTime(d.getTime() + (8*3600*1000) + (time*1000)) //这里获取的时间是GMT格式,比北京时间晚8个小时,需要+8小时 var expires = "expires="+d.toGMTString(); //设置cookie的名称、值、失效时间 document.cookie = name + "=" + value + "; " + expires; } // 获取cookie function getCookieValue(cname) { var name = cname + "="; var ca = document.cookie.split(‘;‘); for(var i=0; i<ca.length; i++) { var c = ca[i].trim(); if (c.indexOf(name)==0) return c.substring(name.length,c.length); } return ""; } //将手机利用ajax提交到后台的发短信接口 function doPostBack(url,backFunc,queryParam) { $.ajax({ async : false, cache : false, type : ‘POST‘, url : url,// 请求的action路径 data:queryParam, success: function (response, status) { console.log(response); console.log(status); }, error: function (xhr, status, error) { console.log(error); console.log(xhr); console.log(status); backFunc } }); } function backFunc1(data){ console.log(data); var d = $.parseJSON(data); if(!d.success){ alert(d.msg); }else{//返回验证码 alert("模拟验证码:"+d.msg); $("#code").val(d.msg); } } //开始倒计时 var countdown; function settime(obj) { countdown=getCookieValue("secondsremained"); if (countdown == 0) { obj.removeAttr("disabled"); obj.removeClass(‘disabled‘) obj.text("获取验证码"); return; } else { obj.attr("disabled", true); obj.addClass(‘disabled‘) obj.text("重新发送(" + countdown + ")"); // console.log(obj.text("重新发送(" + countdown + ")")); countdown--; document.cookie="secondsremained="+countdown+";"; } setTimeout(function() { settime(obj) },1000) //每1000毫秒执行一次 } //校验手机号是否合法 function isPhoneNum(){ var phonenum = $("#phone").val(); var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/; if(!myreg.test(phonenum)){ $("#phone").focus() return false; }else{ return true; } }