我有一个包含一个按钮的表单,该按钮将触发谷歌隐形验证码。我正在使用的 html 页面如下所示:
<html>
<head>
<script src="https://www.google.com/recaptcha/api.js?onload=onLoadRecaptcha&render=explicit" async defer></script>
</head>
<body>
<form method="post" id="signup_form">
<input type="text" name="fullname" value=""/>
<div class="g-recaptcha"
id="formSignup-recaptcha"
data-sitekey="<?php echo $sitekey; ?>"
data-callback="onSubmitFormSignupUser"
data-size="invisible">
</div>
<button type="button" name="submitBtn" id="submitBtn">Submit</button>
</form>
</body>
</html>
但是当我单击#submitBtn
时,我需要使用ajax运行验证过程,以确保在调用/执行google recaptcha之前正确填写所有必填字段。这是我正在使用的 javscript 代码:
var widgetId = '';
var onLoadRecaptcha = function() {
widgetId = grecaptcha.render('submitBtn', {
'sitekey': $('#formSignup-recaptcha').attr('data-sitekey'),
'callback': onSubmitFormSignupUser,
});
};
var onSubmitFormSignupUser = function() {
validateForm('#formSignupUser')
};
var doSubmitFormSignupUser = function(target) {
var postData = $(target);
$.ajax({
url: '/signup_user',
type: 'post',
data: postData,
dataType: 'json',
success: function(res) {
if (res.status) {
window.location.href = '/home/signup_success';
} else {
console.log(res.message);
}
},
error: function(err) {
console.log('error', err.responseText);
},
complete: function() {
grecaptcha.reset(widgetId);
}
});
});
var validateForm = function(target) {
var myData = $(target).serializeArray();
$.ajax({
url: '/is_validated',
type: 'post',
data: myData,
dataType: 'json',
async: false,
success: function(res) {
if (res.status) {
doSubmitFormSignupUser(target);
} else {
console.log('message', res.message);
}
},
error: function(err) {
console.log('error', err.responseText);
},
complete: function() {
grecaptcha.reset(widgetId);
}
});
}
$('body').on('click', '#submitBtn', function(e) {
e.preventDefault();
grecaptcha.execute(widgetId);
});
这是我的 php 代码:
function is_validated()
{
$response = [
'status' => 0,
'message' => '',
];
echo json_encode($response);
}
function signup_user()
{
echo 'thank you for signing up';
}
不知何故,该代码不起作用..每当我点击#submitBtn
时,谷歌验证码会自动出现,要求用户选择所有带有公共(public)汽车或类似内容的图像。我不知道我的代码有什么问题......任何人都可以帮忙吗?
最佳答案
I don't know, Why are you using server side form validation with ajax.
因为,在下面的行中,您将在单击按钮后立即执行 reCaptcha
。
$('body').on('click', '#submitBtn', function(e) {
e.preventDefault();
grecaptcha.execute(widgetId);
});
如果您想在ajax请求
之后执行reCaptcha
,请从上面的 block 中删除行grecaptcha.execute(widgetId);
。并放在这里,
complete: function() {
grecaptcha.execute(widgetId);
}
关于javascript - 如何阻止谷歌验证码执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59930728/