Google reCaptcha 未在客户端验证
Google reCaptcha not validating on client side
服务器端正常,工作正常,但客户端验证无法像下面的代码那样工作:
<script src='https://www.google.com/recaptcha/api.js'></script>
<div class="g-recaptcha" data-sitekey="xxxxx"></div>
<div id="html_element"></div>
JS
<script>
var googleResponse = jQuery('#g-recaptcha-response').val();
if (!googleResponse) {
$('<p style="color:red !important" class=error-captcha"><span class="glyphicon glyphicon-remove " ></span> Please fill up the captcha.</p>" ').insertAfter("#html_element");
return false;
} else {
return true;
}
</script>
我的问题在哪里?
您应该遵循以下代码:
<div id="html_element" style="display: none;color:red !important">
<span class="glyphicon glyphicon-remove " ></span>
Please fill up the captcha.
</div>
$('#form').on('submit', function (e) {
var response = grecaptcha.getResponse();
//recaptcha failed validation
if(response.length == 0) {
e.preventDefault();
$('#html_element').show();
}
//recaptcha passed validation
else {
$('#html_element').hide();
}
if (e.isDefaultPrevented()) {
return false;
} else {
return true;
}
});
服务器端正常,工作正常,但客户端验证无法像下面的代码那样工作:
<script src='https://www.google.com/recaptcha/api.js'></script>
<div class="g-recaptcha" data-sitekey="xxxxx"></div>
<div id="html_element"></div>
JS
<script>
var googleResponse = jQuery('#g-recaptcha-response').val();
if (!googleResponse) {
$('<p style="color:red !important" class=error-captcha"><span class="glyphicon glyphicon-remove " ></span> Please fill up the captcha.</p>" ').insertAfter("#html_element");
return false;
} else {
return true;
}
</script>
我的问题在哪里?
您应该遵循以下代码:
<div id="html_element" style="display: none;color:red !important">
<span class="glyphicon glyphicon-remove " ></span>
Please fill up the captcha.
</div>
$('#form').on('submit', function (e) {
var response = grecaptcha.getResponse();
//recaptcha failed validation
if(response.length == 0) {
e.preventDefault();
$('#html_element').show();
}
//recaptcha passed validation
else {
$('#html_element').hide();
}
if (e.isDefaultPrevented()) {
return false;
} else {
return true;
}
});