发送短信验证码
很简单的一个移动端发送短信验证码的功能,验证码生成及发送(第三方接口)都是后台完成,本文内容只是从前端通过JS发送请求。
<html> <head> <title>GetVerifiedCode</title> </head> <body> <form action="#" method="post"> <input type="number" name="cellphone" id="cellphone" value="${this.params.cellphone}" /> <input id="btnSendVerifiedCode" type="button" value="getVerifiedCode"/> </form> %{--提示信息--}% <div class="message-box"> <div class="helpMsg hide"></div> </div> </body> </html>
<style> .vCodeActive { background-color: #62C16A !important; border: 1px solid #62C16A; font-size: 1.5rem; } .message-box { position: fixed; z-index: 10; width: 100%; top: 30%; display: flex; text-align: center; justify-content: center; } .helpMsg { padding: 2px 10px; line-height: 28px; font-size: 1.2rem; font-weight: 500; text-align: center; background-color: rgba(0, 0, 0, 0.6); border-radius: 5px; color: #fff; } </style>
var time = 30; var interval; $('#btnSendVerifiedCode').click(function () { var cellphone = $("#cellphone").val().trim(); if (!cellphone || !/^(13[0-9]|14[0-9]|15[0-9]|17[0-9]|18[0-9])\d{8}$/.test(cellphone)) { helpMessage("请输入正确的手机号"); return; } $.ajax({ type: "POST", url: "http://" + window.location.host + "/action/sendVerifiedCode", data: { cellphone: cellphone, }, beforeSend:function(){ interval = setInterval(function () { if (time > 0) { $('#btnSendVerifiedCode').attr('disabled', 'disabled').addClass("vCodeActive"); $('#btnSendVerifiedCode').val("" + (time--) + '秒后重试'); } else { $('#btnSendVerifiedCode').removeAttr('disabled').removeClass("vCodeActive"); $('#btnSendVerifiedCode').val("获取验证码"); time = 60; clearInterval(interval); } }, 1000); }, success: function (data) { if (data.status == "success") { helpMessage("验证码发送成功"); } if (data.status == "error") { helpMessage("data.errorMessage"); } } }); }); function helpMessage(message) { $(".helpMsg").text(message).fadeIn(200); setTimeout(function () { $(".helpMsg").fadeOut(200); }, 2000); }