我正在我们的 CMS 应用程序中为网站创建一个表单,该应用程序使用 Google 的新的隐形 reCaptcha。
但是,我一直在纠结如何使用 reCaptcha 的回调?
在使用验证码之前,代码很简单:
HTML
<form>
Form input fields here...
<button id="a23k4l234lj2l-submit-button"></button>
</form>
jQuery
$('#a23k4l234lj2l-submit-button').click(function (e) {
e.preventDefault();
var that = $(this);
if(Abayo.validate(that)) {
Abayo.submit(that);
}
})
Abayo
库具有验证特定表单并将数据发送到处理表单数据的脚本的功能。
现在,我想将 reCaptcha 添加到表单中。 documentation说如下:
1 Create a div with data-size='invisible'.
<div class="g-recaptcha" data-sitekey="your_site_key" data-callback="onSubmit" data-size="invisible"> </div>
2 Call grecaptcha.execute from a javascript method.
grecaptcha.execute();
这有效,但是验证码的回调函数只给我一个响应代码来检查验证用户响应:
The user's response, g-recaptcha-response, will be the input for your callback function.
响应仅告诉我是否可以将我的请求发送到服务器。
我需要的是提交按钮的位置、DOM 元素或任何类型的按钮标识,以便从与按钮匹配的表单中检索数据?
使用以下代码我无法从表单中检索数据并将其发送到服务器?
$('#a23k4l234lj2l-submit-button').click(function (e) {
e.preventDefault();
grecaptcha.execute();
})
var onSubmit = function(response) {
// var that cannot be defined, I don't have a DOM element anywhere?
var that = ????
if(Abayo.validate(that)) {
Abayo.submit(that);
}
}
问题
有没有办法在 reCaptcha 回调中获取 DOM 元素?
最佳答案
您可以以编程方式创建您的验证码。
首先创建您的验证码 div。
<div id="myCaptcha" />
然后呈现验证码并使用 token 传递您的数据。
var that = $(this);
grecaptcha.render('myCaptcha', {
sitekey: 'xxx',
callback: function(token) {
Abayo.submit(token, that)
}
});
更多信息在这里 https://developers.google.com/recaptcha/docs/invisible#js_api
关于javascript - 在不可见的 reCaptcha 回调中传递变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42671854/