如何使用Ajax获取reCAPTCHA数据

问题描述 投票:0回答:1

我想根据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;
    }
}
java php html ajax recaptcha
1个回答
0
投票

如果ajax在为您提供正确的数据,则只需在ajax端检查返回值是human还是bot,具体取决于显示所需的警报。

您的功能将如下所示:

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");
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.