获取短信验证码案例

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <div class="box">
        <input id="input" type="text" value="" />
        <input id="button" onclick="getCode()" type="button" value="获取验证码">
    </div>
</body>
<script>
    function getCode() {


        let input = document.getElementById('input'),
            button = document.getElementById('button'),
            time = 60,
            validCode = true,
            timer;
        if (button.value != '获取验证码') { //此处是没有接口,如果有调短信的接口,此处可不用,接口那里会提示已经发送
            if (button.value == '重新获取验证码') {
                console.log('重新获取验证码')
            }
            else {
                alert('已经发送,请' + button.value + '秒后重新发送')
                return false;
            }
        }
        //这里是请求接口时,放入请求成功时
        if (validCode) {
            validCode = false;
            timer = setInterval(() => {
                button.value = time-- + 's'
                console.log(time);
                if (time == 0) {
                    clearInterval(timer)
                    validCode = true;
                    button.value = '重新获取验证码';
                }
            }, 1000);
        };
        // 有接口案例
        // that.$Request({
        //     url: "url",
        //     data: {
        //         mobile: that.mobile
        //     },
        //     method: "get",
        //     success: function (res) {
        //         if (res.status == 1) {
        //             that.$Message.success(res.msg);
        //             that.message = time + "秒";
        //             if (validCode) {
        //                 validCode = false;
        //                 timers = setInterval(function () {
        //                     time--;
        //                     that.message = time + "秒";
        //                     if (time == 0) {
        //                         clearInterval(timers);
        //                         that.message = "重新发送";
        //                         validCode = true;
        //                     }
        //                 }, 1000);
        //             }
        //         } else {
        //             that.$Message.error("发送短信失败");
        //             clearInterval(timers);
        //             that.message = "重新发送";
        //             validCode = true;
        //         }
        //     }
        // });
    }

</script>

</html>

猜你喜欢

转载自blog.csdn.net/dwb123456123456/article/details/82712826