微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ajax与php小谈手机验证码

在项目中碰到一个写手机验证码的问题,所以写出来:

这是前段页面,使用ajax发送了一个json格式的手机号码过去

<scriptsrc="jquery-1.11.1.min.js"type="text/javascript"></script>
<scripttype="text/javascript">
varInterValObj;//timer变量,控制时间
varcount=120;//间隔函数,1秒执行
varcurCount;//当前剩余秒数
varcode="";//验证码
varcodeLength=4;//验证码长度
functionsendMessage(){
curCount=count;
varphone=$("#phone").val();//手机号码
if(phone!=""){
//设置button效果,开始计时
$("#btnSendCode").attr("disabled","true");
$("#btnSendCode").val("请在"+curCount+"秒内输入验证码");
InterValObj=window.setInterval(SetRemainTime,1000);//启动计时器,1秒执行一次
//向后台发送处理数据
for(vari=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("发送失败");
returnfalse;}*/

alert(json.code);
}
});
}else{
alert("手机号码不能为空!");
}
}
//timer处理函数
functionSetRemainTime(){
if(curCount==0){
window.clearInterval(InterValObj);//停止计时器
$("#btnSendCode").removeAttr("disabled");//启用按钮
$("#btnSendCode").val("重新发送验证码");
code="";//清除验证码。如果不清除,过时间后,输入收到的验证码依然有效
}
else{
curCount--;
$("#btnSendCode").val("请在"+curCount+"秒内输入验证码");
}
}
</script>
</head>
<body>
<form>
<div>
<fontcolor="red">*</font>手机号码:
</div>
<div>
<inputtype="text"id="phone"name="phone"/>
</div>
<div>
<fontcolor="red">*</font>验证码:
</div>
<div>
<inputtype="text"id="checkCode"name="checkCode"size="6"/>
<inputid="btnSendCode"type="button"value="发送验证码"onclick="sendMessage()"/>
</div>
</form>

在接收端,我使用的是TP框架,接收并返回一个随机码:

publicfunctionsend_phone(){
		import('ORG.msgSend');
			$phone=$this->_post('phone');
			$msgsend=newmsgSend();
$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
	/*
	*
	*/
	classmsgSend{
		constMSG_USERNAME='';
		constMSG_PASSWORD='';
		constMSG_URL='';
		constRAMDOM_CODE='1234567890';
		constCODE_LENGTH=4;
		
		publicfunction__construct(){
		}
		
		publicfunctionsendMsg($sendto,$msg){
			$msg=rawurlencode($msg);
			//returnfile_get_contents();
		}
		
		publicfunctionrandom(){
			returnsubstr(str_shuffle(self::RAMDOM_CODE),self::CODE_LENGTH);
		}		
	}
	
?>

测试如图,返回一串随机生成码:

wKiom1R5ciyDh2Y_AAC2lg2WgHI043.jpg

原文地址:https://www.jb51.cc/ajax/164087.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐