在grecaptcha.execute()完成执行后(由事件触发),如何调用函数? [英] How can I call a function after grecaptcha.execute() has finished executing - triggered by an event?

查看:285
本文介绍了在grecaptcha.execute()完成执行后(由事件触发),如何调用函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前 grecaptcha.execute 是在页面加载时执行的,如下面的第一个JS示例所示.如果触发了reCAPTCHA质询,则会在页面加载后发生.理想情况下,这将在单击表单提交按钮时发生.因此,我通过将其移入Submit事件(第二个JS示例)并将axios函数放入promise中来进行了尝试.它在grecaptcha.execute完成执行之前提交.

Currently grecaptcha.execute is being executed on page load as in the first JS example below. If reCAPTCHA challenge is triggered this happens when the page has loaded. Ideally this would happen when the form submit button is clicked instead. So I've tried this by moving this into the submit event (second JS example) and put the axios function into a promise. It's submitting before grecaptcha.execute has finished executing.

我在这里不了解什么?我对诺言的初次体验,难道我不了解诺言如何运作?这不是解决此问题的最佳方法吗?完全是其他东西吗?

What is it that I'm not understanding here? My first experience with promises so am I not understanding how promises work? Is that not the best solution for this problem? Is is something else entirely?

HTML

<head>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" defer></script>
</head>

JS

const form = document.querySelector('#subscribe');
let recaptchaToken;
const recaptchaExecute = (token) => {
    recaptchaToken = token;
};


const onloadCallback = () => {
    grecaptcha.render('recaptcha', {
        'sitekey': 'abcexamplesitekey',
        'callback': recaptchaExecute,
        'size': 'invisible',
    });
    grecaptcha.execute();
};

    form.addEventListener('submit', (e) => {
        e.preventDefault();
        const formResponse = document.querySelector('.js-form__error-message');
        axios({
            method: 'POST',
            url: '/actions/newsletter/verifyRecaptcha',
            data: qs.stringify({
                recaptcha: recaptchaToken,
                [window.csrfTokenName]: window.csrfTokenValue,

            }),
            config: {
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
            },
        }).then((data) => {
            if (data && data.data.success) {
                formResponse.innerHTML = '';
                form.submit();
            } else {
                formResponse.innerHTML = 'Form submission failed, please try again';
            }
        });
    }

JS

const onloadCallback = () => {
    grecaptcha.render('recaptcha', {
        'sitekey': 'abcexamplesitekey',
        'callback': recaptchaExecute,
        'size': 'invisible',
    });
};

form.addEventListener('submit', (e) => {
    e.preventDefault();
    const formResponse = document.querySelector('.js-form__error-message');
    grecaptcha.execute().then(axios({
        method: 'POST',
        url: '/actions/newsletter/verifyRecaptcha',
        data: qs.stringify({
            recaptcha: recaptchaToken,
            [window.csrfTokenName]: window.csrfTokenValue,
        }),
        config: {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
        },
    })).then((data) => {
        if (data && data.data.success) {
            formResponse.innerHTML = '';
            form.submit();
        } else {
            formResponse.innerHTML = 'Form submission failed, please try again';
        }
    });
}

推荐答案

我正在使用Web服务,因为我想要一种可以在所有页面中使用的方法.特别注意您需要返回false的事实;然后当ajax请求返回时,回发您的帖子.

I'm using a web service, as I wanted a method that I could use in all pages. Special attention to the fact you need to return false; and when the ajax request returns, do your post back.

<script type="text/javascript">

   function CheckCaptcha()
    {
        grecaptcha.ready(function () {
            grecaptcha.execute('<%#RecaptchaSiteKey%>', { action: 'homepage' }).then(function (token) {
            $.ajax({
                type: "POST",
                url: "../WebServices/Captcha.asmx/CaptchaVerify", 
                data: JSON.stringify({ 'captchaToken' : token }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    __doPostBack('<%= RegisterButton.UniqueID%>', '');
                    //console.log('Passed the token successfully');
                },
                failure: function (response) {                     
                    //alert(response.d);
                }
                });
            });
       });

       return false;
    }
    </script>

这篇关于在grecaptcha.execute()完成执行后(由事件触发),如何调用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆