"Not a robot" 没有 <form> 而是 AJAX 的重新验证

"Not a robot" recaptcha without a <form> but AJAX instead

使用 "I am not a robot" Recpatcha 的传统方式似乎是在客户端使用 <form>

<form action="post.php" method="POST">
    <div class="g-recaptcha" data-sitekey="6Lc_0f4SAAAAAF9ZA_d7Dxi9qRbPMMNW-tLSvhe6"></div>
    <button type="submit">Sign in</button>
</form>

<script src='https://www.google.com/recaptcha/api.js'></script>

然后一些g-recaptcha-response会被发送到服务器。


但是,在我的代码中我不使用 <form> 而是使用 AJAX 调用:

$('#btn-post').click(function(e) { 
  $.ajax({
    type: "POST",
    url: "post.php",
    data: {
      action: 'post',
      text: $("#text").val(),
      ajaxMode: "true"
    },
    success: function(data) { },
    error: function(data) { } 
  }); } });

如何使用此解决方案获得 g-recaptcha-response 答案?

您使用了一个表单,中断了表单的提交。正常设置表格:

<form action="post.php" method="POST" id="my-form">
    <div class="g-recaptcha" data-sitekey="6Lc_0f4SAAAAAF9ZA_d7Dxi9qRbPMMNW-tLSvhe6"></div>
    <input type="text" id="text">
    <button type="submit">Sign in</button>
</form>

<script src='https://www.google.com/recaptcha/api.js'></script>

然后你用jQuery中断表单的提交和serialize it,允许你通过Ajax:

传递数据
$('#my-form').submit(function(e) {
    e.preventDefault();
    $this = $(this);
    $.ajax({
        type: "POST",
        url: "post.php",
        data: $this.serialize()
    }).done(function(data) {
    }).fail(function( jqXHR, textStatus ) {
        alert( "Request failed: " + textStatus );
    });
});

正如您所注意到的,我使用了 .done.fail 而不是 successerror,这是 preferred way of handling the response

我只是分别在没有使用任何表单和提交机制的情况下实现了它。因此,一个纯粹的 AJAX 解决方案。

HTML代码:

<div id="recaptcha-service" class="g-recaptcha"
 data-callback="recaptchaCallback"
 data-sitekey=""></div>
<script type="text/javascript" src="https://www.google.com/recaptcha/api.js?hl=en"></script>

JavaScript代码:

window.recaptchaCallback = undefined;

jQuery(document).ready(function($) {

  window.recaptchaCallback = function recaptchaCallback(response) {
    $.ajax({
      method: "POST",
      url: "http://example.com/service.ajax.php",
      data: { 'g-recaptcha-response': response },
    })
      .done(function(msg) {
        console.log(msg);
      })
      .fail(function(jqXHR, textStatus) {
        console.log(textStatus);
      });
  }

});

重点是使用回调(recaptchaCallback 在这种情况下)。

您可以在 https://gist.github.com/martinburger/f9f37770c655c25d5f7b179278815084. That example uses Google's PHP implementation on the server side (https://github.com/google/recaptcha) 找到更完整的示例。

为了回答的完整性,假设您只想使用 link 您可以...

<form id="g-recap">
  <div class="g-recaptcha" data-sitekey="{{ gcaptcha key }}" ></div>
</form>
<a href="/recaptchaured/path">Verify</a>

$('a').on('click',function(e) {
   e.preventDefault();
   document.location =  $(this).attr('href') + '?' + $('#g-recap').serialize()
});