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

如何将reCAPTCHA关联到登录按钮并移除独立提交按钮

解决reCAPTCHA与现有登录按钮关联的问题

核心思路是合并两个表单,把reCAPTCHA集成到登录表单中,同时调整按钮逻辑,让登录按钮先触发reCAPTCHA验证,通过后再提交表单。

具体修改步骤:

  • 将reCAPTCHA的<div class="g-recaptcha">移到登录表单内部,删除独立的reCAPTCHA表单
  • 把原登录按钮从type="submit"改为type="button",避免直接提交表单
  • 添加隐藏输入框存储reCAPTCHA验证token,方便后端接收
  • 调整JS逻辑,让登录按钮点击时先检查reCAPTCHA是否完成验证,通过后再提交登录表单

修改后的完整代码

</div>
        
<div id="content">
    <form action="Validation" method="post" id="loginForm">
        <table> 
            <tr><td>UserName: </td><td><input type="text" name="username" value="<%=user%>" /></td></tr>
            <tr><td>Password :</td><td><input type="text" name="password" value="<%=pass%>"/></td></tr>
            <!-- 把reCAPTCHA移到登录表单内 -->
            <tr>
                <td colspan="2">
                    <div class="g-recaptcha" data-sitekey="My site key" data-callback="verifyCaptcha"></div>
                    <div id="g-recaptcha-error"></div>
                    <!-- 隐藏字段存储reCAPTCHA token,供后端验证 -->
                    <input type="hidden" name="g-recaptcha-response" id="g-recaptcha-response">
                </td>
            </tr>
            <!-- 修改按钮类型并绑定验证提交逻辑 -->
            <tr><td><input type="button" name="Login" value="Login" onclick="checkAndSubmitLogin()"/></td></tr>
        </table>  
    </form>

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

// 登录按钮点击触发的验证逻辑
function checkAndSubmitLogin() {
    if(recaptcha_response.length == 0) {
        document.getElementById('g-recaptcha-error').innerHTML = '<span style="color:red;">请完成reCAPTCHA验证</span>';
        return false;
    }
    // 验证通过,提交登录表单
    document.getElementById('loginForm').submit();
}

function verifyCaptcha(token) {
    recaptcha_response = token;
    // 将token存入隐藏字段
    document.getElementById('g-recaptcha-response').value = token;
    document.getElementById('g-recaptcha-error').innerHTML = '';
}
</script>

关键说明

  1. 合并表单后,用户名、密码、reCAPTCHA token会一同提交到Validation接口,后端需要同时验证用户信息和reCAPTCHA token
  2. 隐藏字段g-recaptcha-response是Google reCAPTCHA要求的标准字段名,后端可通过该字段获取验证token
  3. 点击登录按钮时先校验recaptcha_response是否有值,确保用户已完成人机验证,否则提示错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 06:25:21