如何jQuery验证ReCaptcha?

时间:2016-07-23 14:01:27

标签: php jquery jquery-validate recaptcha

Recaptcha表格是这样的:

    <script type="text/javascript"> var RecaptchaOptions = {"theme":"red","lang":"en"}; </script><script type="text/javascript" src="https://www.google.com/recaptcha/api/challenge?k=6LeThAsTAAAAAKYRjSpA8XZ1s4izK65hYr9ulCiD"> </script><noscript> <iframe src="https://www.google.com/recaptcha/api/noscript?k=6LeThAsTAAAAAKYRjSpA8XZ1s4izK65hYr9ulCiD" height="300" width="500" frameborder="0"> </iframe><br> <textarea name="recaptcha_challenge_field" rows="3" cols="40"> </textarea> <input type="hidden" name="recaptcha_response_field" value="manual_challenge"> </noscript>

和ZC2 for ReCaptcha的验证器是这样的:

 $recaptcha = new ZendService\ReCaptcha\ReCaptcha(PUB_KEY, PRIV_KEY);
 $html = $recaptcha->getHTML();
 $result = $recaptcha->verify($_POST['recaptcha_challenge_field'], $_POST['recaptcha_response_field']);
 if (!$result->isValid()) {
  // invalid
 } else {
 // valid
 }

可以像这样远程验证它:https://jqueryvalidation.org/remote-method

我在远程php文件中尝试过,但它不起作用:

$recaptcha = new ZendService\ReCaptcha\ReCaptcha(PUB_KEY, PRIV_KEY);
$result = $recaptcha->verify($_GET['recaptcha_challenge_field'], $_GET['recaptcha_response_field']);
if (!$result->isValid()) {
echo json_encode(false);
} else {
echo json_encode(true);
}

和js本身是:

$().ready(function() {
$("#contact").validate({
                      rules: {
                               recaptcha_response_field: {
                                          required: true,
                                          remote: "json.php"
                               }             
                  }   
 });
 });

是否有可能或我做错了什么?

1 个答案:

答案 0 :(得分:0)

尝试此功能验证recaptcha

var grecaptchaId;
        var onloadCallback = function () {
            grecaptchaId = grecaptcha.render('grecaptcha', {
                'sitekey': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
                'callback': function (response) {
                    $("#grecaptcha_error").text('');
                }
            });
        };

        function ValidateRecaptcha() {
            var x;
            x = grecaptcha.getResponse(grecaptchaId);
            if (x != "") {
                $("#grecaptcha_error").text('');
                return true;
            }
            else {
                $("#grecaptcha_error").text('The captcha is required and can\'t be empty');
                return false;
            }
        }