隐形Google验证码v2无法正常运行

时间:2018-09-28 20:14:38

标签: javascript ajax recaptcha invisible-recaptcha

在第一次提交所有有效数据并正确提交表单时,以下代码可以正常工作。如果提交表单后服务器端发生任何错误,则当用户重新提交表单时,recaptcha不会重置。 以下是示例代码:

html格式

<script src="https://www.google.com/recaptcha/api.js"></script>
<div>
<form name="signupForm"  method="POST" action="/signup">
    <div class="form-group mobile-number">
        <input type="tel" id="mobileNo" class="form-control" name="mobileNumber" maxlength="10"
               autofocus>

    <label for="mobile"> Your Mobile no. </label>
    </div>
    <div class="g-recaptcha"
        data-sitekey="{key}"
        data-callback="setResponse"
        data-badge="inline"
        data-size="invisible">
    </div>
    <input type="hidden" id="captcha-response" name="captcha-response"/>
    <button id="submitButon" type="submit">Sign me up!</button>
</form>
</div>

javascript

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<script>
    function setResponse(response) {
        document.getElementById('captcha-response').value = response;
        submitForm();
    }

    function submitForm() {
        var $form = $("form");
        var data = JSON.stringify($form.serializeObject());
        var myJsonObject = JSON.parse(data);

        data = JSON.stringify(myJsonObject);

        $.ajax({
            type: "POST",
            url: "dummy url",
            contentType: "application/json",
            xhrFields: {withCredentials: true},
            data: data,
            success: function (data, textStatus, request) {
                // success
            },
            error: function (xhr, err) {
                // logics here
                grecaptcha.execute();
                setResponse;
            }
        });
    }
</script>

<script>
    jQuery(document).ready(function () {

        //homepage form
        $('form[name="signupForm"]').validate({
            onfocusout: function (element) {
                $(element).valid();
            },
            rules: {
                mobileNumber: {
                    required: true,
                    minlength: 10,
                    maxlength: 10
                }
            },
// Specify validation error messages
            messages: {
                mobileNumber: "A valid mobile number is of 10-digit",

            },
//submit handler
            submitHandler: function (form) {
                submitForm();
            }
        });
    });
</script>

我认为错误是在ajax调用中,但无法弄清验证码为何不再次重置。

0 个答案:

没有答案