首页 > 解决方案 > 使用js将令牌值添加到html表单

问题描述

我正在尝试将 google recaptcha 3 添加到我的 html 表单中。当我在页面加载时调用它时会发现作品,但由于它在 2 分钟后过期并且应该在准备好时调用,我试图将它添加到我的提交函数中,但不知道在哪里做错了。

我的js代码是:

     <script>
                    
                    
  $(document).ready(function () {
    $('.regformsubmit').click(function (e) {
        
        grecaptcha.execute('6LcVzjYcmykey is here', {action: 'validate_captcha'}).then(function(token) {
                // add token to form
                $("#register_form").prepend('<input type="hidden" name="g-recaptcha-response" id="g-recaptcha-response" value="' + token + '">');
        });
              
      var myForm = jQuery( "#register_form" );

  if ( ! myForm[0].checkValidity() )
  {
    // bonk! failed to validate, so return true which lets the
    // browser show native validation messages to the user
    return true;
  }
      e.preventDefault();
      var country = $('#country').val();
      var fname = $('#fname').val();
        var lname = $('#lname').val();
        var emailid = $('#emailid').val();
        var password = $('#password').val();
        var confirm_password = $('#confirm_password').val();
        var phone = $('#phone').val();
        var vcode = $('#vcode').val();
        var upline = $('#upline').val(); 
        var agree_term = $('#agree_term').val(); 
        var cr = $('#g-recaptcha-response').val(); 
      $.ajax
        ({
          type: "POST",
          url: "process-reg.php",
          data: { "country": country,"fname":fname, "lname": lname, "emailid": emailid, "password": password, "confirm_password": confirm_password, "phone": phone, "vcode": vcode, "upline": upline, "agree_term": agree_term, "cr": cr },
          success: function (data) {
            $('#RegResult').html(data);
            $('#register_form')[0].reset();
          }
        });
    });
  });
</script>

标签: javascripthtmlformsrecaptcha-v3

解决方案


推荐阅读