Table of Contents
推荐答案
Home Backend Development PHP Tutorial 求js代码能够将用户输入的手机号,验证,并传入后台的代码

求js代码能够将用户输入的手机号,验证,并传入后台的代码

May 01, 2017 am 10:15 AM

前端页面如下

求js代码能够将用户输入的手机号,验证,并传入后台的代码

<p class="form-group">
    {!! Form::label('phone','新手机号',['class' => 'col-md-2 control-label']) !!}
    <p class="col-md-5">
        {!! Form::text('phone',null,['class'=>'form-control']) !!}
    </p>
    <p class="col-md-4">
        <p class="form-control-static">
        <a href="#">发送验证码</a>
        </p>
    </p>
</p>
Copy after login

后台发送方法位sendVerifyMessage,对应的路由为domain/send-verify-message
求js代码能够将用户输入的手机号,验证,并传入后台的代码。

回答:

需要jquery 和 jquery.cookie

var SendCode = (function($, Cookies) {
    return {
        _config : {sendObj:$('#sendCode'), mobile:$('input[name=mobile]')},
        _timer : null,
        /**
         * 初始化发化验证码类
         *
         */
        init : function(config) {
            this._initDisable();
            $.extend(this._config, config);
            
            return this;
        },
        /**
         * 异步检查手机号是否合法
         */
        AsynCheckMobile : function(url, data, successCallback, errorCallback) {
            this.doPost({ url: url, data:data, successCallback:successCallback, errorCallback:errorCallback});
        },
        /**
         *    发送验证码
         */         
        sendCode : function(url, data, successCallback, errorCallback) {
            this.doPost({ url: url, data:data, successCallback:successCallback, errorCallback:errorCallback});
        },
        /**
         * 异步交互动作
         */
        doPost : function(params) {
            if (toString.call(params.successCallback) !== "[object Function]") {
                params.successCallback = function() {};
            }
            
            if (toString.call(params.errorCallback) !== "[object Function]") {
                params.errorCallback = function() {};
            }
            
            var _this = this;
            $.ajax({
                url : params.url,
                data : params.data,
                type : 'post',
                dataType : 'json',
                success : function(result) {
                    if (result.code == 200) {
                        params.successCallback.call(_this, result);
                    } else {
                        params.errorCallback.call(_this, result);
                    }
                }
            })
        },
        checkMobile: function() {
            return /\d{11}/.test(this._config.mobile.val());
        },
        /**
         *    禁用按钮
         */
        _disableButton : function() {
            
            var TotalSeconds = 60;
            var storeState = Cookies.getJSON('state');
            storeState = storeState || {TotalSeconds:TotalSeconds, enable:false};
            Cookies.set('state', JSON.stringify(storeState), {path:''});
            this._config.sendObj.prop('disabled', true);
            var _this = this;
            this._timer = setInterval(function() {
                var _state = Cookies.getJSON('state');
                if (_state.TotalSeconds <= 0) {
                    clearInterval(_this._timer);
                    Cookies.remove(&#39;state&#39;, { path: &#39;&#39; });
                    _this._config.sendObj.removeAttr(&#39;disabled&#39;);
                    _this._config.sendObj.html(&#39;发送验证码&#39;);
                } else {
                    _this._config.sendObj.html(_state.TotalSeconds + &#39;秒后发送&#39;);
                    _state.TotalSeconds -= 1;
                    Cookies.set(&#39;state&#39;, _state, {path:&#39;&#39;})
                }
            }, 1000);
        },
        _initDisable : function() {
            var _state = Cookies.getJSON(&#39;state&#39;);
            if (_state) {
                this._disableButton();
            }
        }
    }
})(jQuery, Cookies);
Copy after login
   var AsynV = {
        &#39;asynValidateCode&#39; : function(data, successCallback, errorCallback) {
            data = data || { code:$(&#39;input[name=captcha]&#39;).val()};
            successCallback = successCallback || function() { return true;};
            errorCallback = errorCallback || function() {return false;};
            $.post(&#39;/simple/_asyn_check_code&#39;, data, function(result) {
                if (200 == result.code) {
                    (successCallback)();
                } else {
                    (errorCallback)();
                }
            }, &#39;json&#39;);
        }
    };
    
    SendCode.init();
    $(&#39;#sendCode&#39;).bind(&#39;click&#39;, function() {
    
        var captcha = $(&#39;input[name=captcha]&#39;).val();
        if (captcha != &#39;&#39;) {
            AsynV.asynValidateCode({ code:captcha}, function() {
                if (SendCode.checkMobile()) {
                    SendCode.sendCode(&#39;/simple/_send_mobile_validate_code&#39;, { mobile:SendCode._config.mobile.val()}, function(result) {
                        alert(result.message);
                        this._disableButton();
                    }, function(result) {
                        alert(result.message);
                    });
                } else {
                    alert(&#39;不正确的手机号&#39;);
                }
            }, function() {
                alert(&#39;图形验证码不正确&#39;);
            });
        } else {
            alert(&#39;请先输入图形验证码&#39;);
        }
        
    });
Copy after login

推荐答案

HTML:

<p class="form-group">
    {!! Form::label('phone','新手机号',['class' => 'col-md-2 control-label']) !!}
    <p class="col-md-5">
        {!! Form::text('phone',null,['class'=>'form-control']) !!}
    </p>
    <p class="col-md-4">
        <p class="form-control-static">
        <a id="send-captcha" href="#">发送验证码</a>
        </p>
    </p>
</p>
Copy after login

JS:

<script>
    // 定义按钮btn
    var btn = $("#send-captcha");
         
    // 定义发送时间间隔(s)
    var SEND_INTERVAL = 60;
    var timeLeft = SEND_INTERVAL;
    
    /**
    * 绑定btn按钮的监听事件
    */
    var bindBtn = function(){
        btn.click(function(){
            // 需要先禁用按钮(为防止用户重复点击)
            btn.unbind('click');
            btn.attr('disabled', 'disabled');
            $.ajax({
                // ajax接口调用...
            })
            .done(function () {
                alert('发送成功');
                //成功
                timeLeft = SEND_INTERVAL;
                timeCount();                
            })
            .fail(function () {
                //失败,弹窗
                alert('发送失败');

                // ** 重要:因为发送失败,所以要恢复发送按钮的监听 **
                bindBtn();
                btn.remove('disabled');
            });
        })
    }           
    
    /**
    * 重新发送计时
    **/ 
    
    var timeCount = function() {
        window.setTimeout(function() {
            if(timeLeft > 0) {
                timeLeft -= 1;
                btn.html(timeLeft + "后重新发送");
                timeCount();
            } else {
                btn.html("重新发送");
                bindBtn();
            }
        }, 1000);
    }
</script>
Copy after login
                               
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

See all articles