加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ajax与php小谈(手机验证码)

发布时间:2020-12-16 02:12:26 所属栏目:百科 来源:网络整理
导读:在项目中碰到一个写手机验证码的问题,所以写出来: 这是前段页面,使用ajax发送了一个json格式的手机号码过去 scriptsrc="jquery-1.11.1.min.js"type="text/javascript"/scriptscripttype="text/javascript"varInterValObj;//timer变量,控制时间varcount=1

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

这是前段页面,使用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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读