【问题标题】:How to get reCAPTCHA data with Ajax如何使用 Ajax 获取 reCAPTCHA 数据
【发布时间】:2020-09-20 11:21:59
【问题描述】:

我想根据 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;
    }
}

【问题讨论】:

  • 当你在 if - else 循环之前使用 console.log($reCAPTCHA) - 你会得到什么?

标签: java php html ajax recaptcha


【解决方案1】:

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

你的函数看起来像:

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");
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-07
    • 2019-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多