html代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="jquery.min.js"></script> </head> <body> 手机号:<input id="mobile" type="text" name="mobile" value=""> <input id="btnSendCode" type="button" value="发送验证码" onclick="sendMessage()" /><br> 验证码:<input id="code" type="text" name="mobile" value=""> </body> </html>
js代码
<script> var timeController; //timer变量,控制时间 var count = 5; //间隔函数,1秒执行 var remainCount;//当前剩余秒数 function sendMessage() { remainCount = count; //设置button效果,开始计时 $("#btnSendCode").attr("disabled", "true"); $("#btnSendCode").val("请在" + remainCount + "秒内输入验证码");//加上这一句不会出现延迟,否则倒计时延迟1s timeController = setInterval("SetRemainTime()", 1000); //启动计时器,1秒执行一次 //向后台发送处理数据 var mobile = document.getElementById("mobile").value; $.ajax({ type: "POST", //用POST方式传输 url: 'f.php', //目标地址. dataType: "json", //数据格式:JSON //data: "dealType=" + dealType +"&uid=" + uid + "&code=" + code, data: "&a="+mobile, success: function(json){ document.getElementById("code").value=json.code; } }); } //timer处理函数 function SetRemainTime() { if (remainCount==0) { clearInterval(timeController);//停止计时器 $("#btnSendCode").removeAttr("disabled");//启用按钮 $("#btnSendCode").val("重新发送验证码"); } else { remainCount--; $("#btnSendCode").val("请在" + remainCount + "秒内输入验证码"); } } </script>
后台文件(f.php)
<?php sleep(5); echo json_encode(array('code'=>mt_rand(1000,9999))); ?>
效果