You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google reCAPTCHA V2中grecaptcha.getResponse()返回空值的原因及解决办法

reCAPTCHA勾选后grecaptcha.getResponse()返回空的原因及解决办法

我尝试在勾选reCAPTCHA复选框后获取响应,JS代码如下:

$('.button').click(function(e){
    e.preventDefault();
    
    //Trying to get the reCAPTCHA response
    var sResponse = grecaptcha.getResponse();
    alert(sResponse); //But this is empty
});

HTML代码:

<div class="g-recaptcha" data-sitekey="MY_SITE_KEY_HERE"></div>

reCAPTCHA显示正常,但勾选复选框后grecaptcha.getResponse()仍返回空字符串,不过直接提交表单到PHP时,能获取到$_POST['g-recaptcha-response']的值。

原因分析

  • 初始化时机不匹配:reCAPTCHA虽然显示正常,但grecaptcha.getResponse()可能在widget未完全初始化完成时被调用,自动渲染的widget未正确绑定到grecaptcha对象上。
  • 缺少widget ID参数:自动渲染模式下,grecaptcha.getResponse()默认需要传入对应widget的ID,若不传,即使单个widget也可能无法正确读取响应值。
  • 事件绑定过早:如果按钮点击事件的绑定逻辑在reCAPTCHA脚本加载完成前执行,此时grecaptcha对象未完全就绪,调用方法会失效。

解决办法

办法1:用验证回调函数存储响应值

给reCAPTCHA添加data-callback属性,验证成功时自动触发回调,将响应值存入全局变量,点击按钮时直接读取:

  1. 修改HTML:
<div class="g-recaptcha" data-sitekey="MY_SITE_KEY_HERE" data-callback="onCaptchaSuccess"></div>
  1. 添加JS代码:
let captchaResponse = '';

function onCaptchaSuccess(response) {
    captchaResponse = response;
}

$('.button').click(function(e){
    e.preventDefault();
    alert(captchaResponse);
});

办法2:手动渲染reCAPTCHA并获取widget ID

放弃自动渲染,手动调用grecaptcha.render创建widget,拿到ID后传入getResponse:

  1. 修改HTML:
<div id="captcha-container"></div>
  1. 修改JS代码:
window.onload = function() {
    const widgetId = grecaptcha.render('captcha-container', {
        sitekey: 'MY_SITE_KEY_HERE'
    });

    $('.button').click(function(e){
        e.preventDefault();
        const sResponse = grecaptcha.getResponse(widgetId);
        alert(sResponse);
    });
};

办法3:确保JS代码在reCAPTCHA加载完成后执行

坚持自动渲染的话,等待reCAPTCHA脚本加载完成后再绑定点击事件:

function waitForCaptchaReady() {
    if (typeof grecaptcha !== 'undefined' && grecaptcha.getResponse) {
        $('.button').click(function(e){
            e.preventDefault();
            const sResponse = grecaptcha.getResponse();
            alert(sResponse);
        });
    } else {
        setTimeout(waitForCaptchaReady, 100);
    }
}

waitForCaptchaReady();

内容的提问来源于stack exchange,提问作者programmer777

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 17:47:26