我想将 reCaptcha V3 添加到表单中。
这是表格:
<form action="mail.php" method="POST">
<!-- This hidden input will contain the token -->
<input type="hidden" name="token" id="token" />
<input type="text" name="name" />
<input type="text" name="email" />
<textarea name="message"></textarea>
<input type="submit" name="submit" value="Send" />
</form>
现在我正在尝试将token值发送到mail.php,所以有一个插件叫做jquery.form我用它来发送 Ajax 请求。
这是 Javascript/Jquery 代码:
$('form').ajaxForm({
beforeSubmit: function() {
//Captcha part
grecaptcha.ready(function() {
grecaptcha.execute('My_website_key', {action: 'form'}).then(function(token) {
//Set token value to the hidden element
$('#token').val(token);
});
});//reCaptcha ready
},//Before submit function
success: function(msg) {
if(msg == 'Message has been sent.'){
console.log('success!');
}else{
console.log(msg);
}
},//success function
complete: function(xhr) {
console.log(xhr.responseText);
}//complete function
});//End Ajax
当我提交表单时,然后我查看控制台,我看到它token是空的,似乎success函数被执行,在token隐藏元素获取令牌之前。
我无法在页面加载或任何其他操作时添加令牌,因为它在 2 分钟后过期,所以我需要获取令牌并将其发送到 PHP 文件。