h5页面短信验证相信大家已经做的很多
其中除了调取接口最关键的在于倒计时,该怎么做看代码吧
html
<div class="form" id="form">
<div class="con">
<div class="input-item">
<input type="tel" name="mobile" maxlength="11" placeholder="输入您的手机号" data-valid="tel" />
</div>
<div class="input-item">
<input class="code-input" type="text" name="imgCode" placeholder="短信验证码" maxlength="4" />
<a href="javascript:;" class="btn" data-countdown="60" id="smsBtn">点击发送</a>
<!--data-countdown需要加上,倒计时方法这个就是记时时长-->
</div>
<a href="javascript:;" class="btn btn-sub" id="subBtn" data-submit="#form"></a>
</div>
</div>
倒计时方法
js方法
countdown: function (name, ticker) {
var timeout = $('[data-countdown]').attr('data-countdown');
var timer;
if (this.timers[name]) {
timer = this.timers[name];
} else {
function Timer(name, timeout) {
this.tid = null;
this.name = name;
this.timeout = this._timeout = timeout;
}
Timer.prototype = {
reset: function () {
this.timeout = this._timeout;
},
tick: function (fun) {
var me = this;
var tick = function () {
me.timeout -= 1;
fun && fun(me.timeout);
if (me.timeout <= 0) {
me.clearInterval();
me.reset();
}
}
this.tid && clearInterval(this.tid);
this.tid = setInterval(tick, 1000);
tick();
},
clearInterval: function () {
clearInterval(this.tid);
}
}
timer = new Timer(name, timeout);
this.timers[name] = timer;
}
timer.tick(function (rest) {
ticker && ticker(rest);
});
},
那么我们怎么用这个方法呢,很简单
点击 smsBtn 按钮的时候触发这个方法,当然这个需要在点击后调取发送短信的接口代码如下`
sendSMSCode: function() {
var self = this;
var inputTel = $('[name="mobile"]').val();
//判断验证手机号格式
if (!/^1[3-9]\d{9}$/.test(inputTel)) {
helper.popup('请输入正确的手机号');
return;
}
//发送的参数与durl请求地址需要根据你自己的项目加入,这里我就空着了
var postData = {你请求的参数 };
var durl =" 你请求地址";
$.ajax({
url: durl,
type: 'post',
data: JSON.stringify(postData),
dataType: 'json',
contentType: 'application/json; charset=UTF-8',
success: function (res) {
//根据状态码判断
if(res.result == 'true' && res.errorcode == '00\n' || res.errorcode == '00') {
//调取coutdown方法
self.countdown('timer',function(res) {
// silent是一个事先写好的class名,里面可以自己加样式如字体 颜色,背景等,点击发送信息按钮,按钮的样式就会改变
$('#smsBtn').addClass('silent').text('重新发送(' + res + ')');
if (res == 0) {
$('#smsBtn').removeClass('silent').text('发送验证码');
}
});
} else {
alert("服务器有误")
}
},
error: function (res) {
helper.loading(false);
helper.popup('网络错误,请重试')
}
});
},
最后其实有个验证的问题,点击提交的时候判断是否已经发送过验证码,可以直接在全局定义一个变量,然后短信发送成功给这个变量赋值,那样就可以通过判断这个值来验证是否发送过短信。
这样整个流程就结束了,欢迎大神们的指教,最后也祝大家10.1快乐。
心酸,还没买到回家的票啊啊啊啊啊