在项目中碰到一个写手机验证码的问题,所以写出来:
这是前段页面,使用ajax发送了一个json格式的手机号码过去
<
script
src
=
"jquery-1.11.1.min.js"
type
=
"text/javascript"
></
script
>
<
script
type
=
"text/javascript"
>
var InterValObj; //timer变量,控制时间
var count = 120; //间隔函数,1秒执行
var curCount;//当前剩余秒数
var code = ""; //验证码
var codeLength = 4;//验证码长度
function sendMessage() {
curCount = count;
var phone=$("#phone").val();//手机号码
if(phone != ""){
//设置button效果,开始计时
$("#btnSendCode").attr("disabled", "true");
$("#btnSendCode").val("请在" + curCount + "秒内输入验证码");
InterValObj = window.setInterval(SetRemainTime, 1000); //启动计时器,1秒执行一次
//向后台发送处理数据
for (var i = 0; i < codeLength; i++) {
code += parseInt(Math.random() * 9).toString();
}
$.ajax({
type: "post", //用POST方式传输
dataType: "json", //数据格式:JSON
url: 'http://192.168.1.100/cancertool/index.php?g=home&m=Api&a=send _phone', //目标地址
data: {"phone":phone},
//error: function (XMLHttpRequest, textStatus, errorThrown) { },
success: function(json){
/*if(json.success==1){
alert("发送成功");
}else{
alert("发送失败");
return false;}*/
alert(json.code);
}
});
}else{
alert("手机号码不能为空!");
}
}
//timer处理函数
function SetRemainTime() {
if (curCount == 0) {
window.clearInterval(InterValObj);//停止计时器
$("#btnSendCode").removeAttr("disabled");//启用按钮
$("#btnSendCode").val("重新发送验证码");
code = ""; //清除验证码。如果不清除,过时间后,输入收到的验证码依然有效
}
else {
curCount--;
$("#btnSendCode").val("请在" + curCount + "秒内输入验证码");
}
}
</
script
>
</
head
>
<
body
>
<
form
>
<
div
>
<
font
color
=
"red"
>*</
font
>手机号码:
</
div
>
<
div
>
<
input
type
=
"text"
id
=
"phone"
name
=
"phone"
/>
</
div
>
<
div
>
<
font
color
=
"red"
>*</
font
>验证码:
</
div
>
<
div
>
<
input
type
=
"text"
id
=
"checkCode"
name
=
"checkCode"
size
=
"6"
/>
<
input
id
=
"btnSendCode"
type
=
"button"
value
=
"发送验证码"
onclick
=
"sendMessage()"
/>
</
div
>
</
form
>
在接收端,我使用的是TP框架,接收并返回一个随机码:
public
function
send_phone(){
import (
'ORG.msgSend'
);
$phone
=
$this
->_post(
'phone'
);
$msgsend
=
new
msgSend();
$code
=
$msgsend
->random();
//生成随机数
$msg
=
'你的验证码为:'
.
"$code"
;
//$res=$msgsend->sendMsg($phone,$msg);
if
(isset(
$msg
)){
$this
->data[
'code'
]=
$code
;
$this
->ajaxReturn(
$this
->data,
'JSON'
);
//$this->ajaxReturn($this->data,'JSON');
}
else
{
$this
->data[
'code'
]=0;
$this
->ajaxReturn(
$this
->data,
'JSON'
);
}
}
msgSend类:
<?php
/*
*
*/
class
msgSend{
const
MSG_USERNAME=
''
;
const
MSG_PASSWORD=
''
;
const
MSG_URL=
''
;
const
RAMDOM_CODE=
'1234567890'
;
const
CODE_LENGTH = 4;
public
function
__construct(){
}
public
function
sendMsg(
$sendto
,
$msg
){
$msg
= rawurlencode(
$msg
);
//return file_get_contents();
}
public
function
random(){
return
substr
(
str_shuffle
(self::RAMDOM_CODE), 0,self::CODE_LENGTH);
}
}
?>