<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <input type="button" id="btn" value="免費獲取驗證碼" onclick="settime(this)" /> <script type="text/javascript"> var countdown = 60; function settime(obj) { if (countdown == 0) { obj.removeAttribute("disabled"); obj.value="免費獲取驗證碼"; countdown = 60; return; } else { obj.setAttribute("disabled", true); obj.value="重新發送(" + countdown + ")"; countdown--; } setTimeout(function() { settime(obj) } ,1000) } </script> </body> </html>
這個只是一種比較簡單的實現方式(頁面刷新就會失效,不過還有一種無視頁面刷新的)
<input id="second" type="button" value="免費獲取驗證碼" />
//發送驗證碼時添加cookie function addCookie(name,value,expiresHours){ var cookieString=name+"="+escape(value); //判斷是否設置過期時間,0代表關閉瀏覽器時失效 if(expiresHours>0){ var date=new Date(); date.setTime(date.getTime()+expiresHours*1000); cookieString=cookieString+";expires=" + date.toUTCString(); } document.cookie=cookieString; } //修改cookie的值 function editCookie(name,value,expiresHours){ var cookieString=name+"="+escape(value); if(expiresHours>0){ var date=new Date(); date.setTime(date.getTime()+expiresHours*1000); //單位是毫秒 cookieString=cookieString+";expires=" + date.toGMTString(); } document.cookie=cookieString; } //根據名字獲取cookie的值 function getCookieValue(name){ var strCookie=document.cookie; var arrCookie=strCookie.split("; "); for(var i=0;i<arrCookie.length;i++){ var arr=arrCookie[i].split("="); if(arr[0]==name){ return unescape(arr[1]); break; }else{ return ""; break; } } }
主要邏輯代碼
$(function(){
$("#second").click(function (){
sendCode($("#second"));
});
v = getCookieValue("secondsremained");//獲取cookie值
if(v>0){
settime($("#second"));//開始倒計時
}
})
//發送驗證碼
function sendCode(obj){
var phonenum = $("#phonenum").val();
var result = isPhoneNum();
if(result){
doPostBack('${base}/login/getCode.htm',backFunc1,{"phonenum":phonenum});
addCookie("secondsremained",60,60);//添加cookie記錄,有效時間60s
settime(obj);//開始倒計時
}
}
//將手機利用ajax提交到后台的發短信接口
function doPostBack(url,backFunc,queryParam) {
$.ajax({
async : false,
cache : false,
type : 'POST',
url : url,// 請求的action路徑
data:queryParam,
error : function() {// 請求失敗處理函數
},
success : backFunc
});
}
function backFunc1(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.val("免費獲取驗證碼");
return;
} else {
obj.attr("disabled", true);
obj.val("重新發送(" + countdown + ")");
countdown--;
editCookie("secondsremained",countdown,countdown+1);
}
setTimeout(function() { settime(obj) },1000) //每1000毫秒執行一次
}
//校驗手機號是否合法
function isPhoneNum(){
var phonenum = $("#phonenum").val();
var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
if(!myreg.test(phonenum)){
alert('請輸入有效的手機號碼!');
return false;
}else{
return true;
}
}
參考鏈接:https://www.oschina.net/code/snippet_2001568_48311
