java - 如何使用 Ajax 获取 reCAPTCHA 数据
问题描述
我想根据 reCAPTCHA 分数使用 Ajax 获得“人类”或“机器人”,但它不起作用......你能给我任何建议吗?此时您无需考虑验证。
html
<form id="contact-form" action="/" method="POST">
<input type="hidden" name="recaptchaResponse" id="recaptchaResponse" />
<input class="btn-send" type="button" name="send" value="SUBMIT">
</form>
脚本(ajax)
$(function() {
$('.btn-send').on('click', function(e){
e.preventDefault();
//reCAPTCHA
grecaptcha.ready(function() {
grecaptcha.execute('my_key_here', {action: 'homepage'}).then(function(token) {
var recaptchaResponse = document.getElementById('recaptchaResponse');
recaptchaResponse.value = token;
});
});
//ajax
var formData = $('#contact-form');
$.ajax({
url: "/",
type: "POST",
data: formData.serialize()
})
.then(
function (data) {
//I want to alert "human" or "bot" here
alert(data);
},
function () {
alert("fail");
});
}
});
php
if (isset($_POST['recaptchaResponse']) && !empty($_POST['recaptchaResponse'])) {
$secret = 'my_key_here';
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['recaptchaResponse']);
$reCAPTCHA = json_decode($verifyResponse);
if ($reCAPTCHA->score >= 0.7) {
echo 'human';
exit;
} else {
echo 'bot';
exit;
}
}
解决方案
如果 ajax 为您提供正确的数据,那么只需在您的 ajax 端检查返回值是否为human
或bot
取决于显示所需的 alert 。
您的功能将如下所示:
function(data) {
var values = $.trim(data); //triming value if there is any whitespaces
if (values == "human") {
alert("Hello you are human"); //show alert
} else {
alert("Hello you are Robot");
}
}
推荐阅读
- python - Pandas 行之间差异的总和
- garbage-collection - jvm old gc 会标记所有堆还是只标记旧堆?
- ruby-on-rails - 没有路由匹配导致 ActionController UrlGenerationError
- java - Mockito - 即使使用了returns_self,模拟构建器也会返回一个空对象
- amazon-s3 - 使用 MediaConvert 时的 AWS S3 文件命名
- python - 将具有相同键的字典列表转换为高数据框
- python - 如何有效地创建使用多处理输入数据的对象迭代器?
- python - 如何为 Google Cloud Pubsub“创建”/“分配”日志处理程序?
- c# - 无法形成连接 ASP.NET 网络路径
- python-3.x - 如何从 Youtube Data API v3 获取最大搜索结果?