如何使用JS自动提交表单

时间:2019-05-27 01:11:49

标签: javascript php html

页面加载完成后,我想使用JS添加代码自动提交表单 我也需要提交输入值 当我单击手动自动工作但未输入“ g-recaptcha-response”值来提交时,提交和验证码响应效果很好
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://www.google.com/recaptcha/api.js?render=<?php echo $captcha_site_key ?>"></script>
</head>
    <form action="check.php" id="myform" method="POST">
    <input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response">
    <input type="Submit" name="Submit">
</form>
<script>
    grecaptcha.ready(function() {
        grecaptcha.execute('<?php echo $captcha_site_key ?>', {action:'validate_captcha'})
                  .then(function(token) {
            document.getElementById('g-recaptcha-response').value = token;
        });
    });
</script>
<script type="text/javascript">
window.onload = function(){
  document.getElementById("myform").submit();
}
</script>

</body>
</html>

2 个答案:

答案 0 :(得分:0)

使用Javascript,您可以通过以下小技巧来实现自己的目标:

使用普通Javascript-这是提交表单的方式:

  document.getElementById("YourFormIdHere").submit();

如果您希望仅在提供验证码时才提交该表格,则必须运行if语句。

首先停止提交表单,以便您可以在提交验证码之前对其进行评估。

document.getElementById("FormIdHere").addEventListener("submit", function(event) {
  event.preventDefault()
});

从此处,您要检查验证码值是否已提交。首先尝试获取验证码的价值

var Captcha = document.GetElementById("capture ID here").value;

//check if captcha has value
if(Captcha){
    //then submit your form here
    document.getElementById("YourFormIdHere").submit();
}

如果验证码值为空,则表单将不会提交,从而迫使用户创建验证码。

答案 1 :(得分:0)

感谢@Mosia Thabo为我提供帮助

JS代码是

说明:-第一个setAttribute值=令牌

然后等待1秒钟,然后提交myform

<script type="text/javascript">
    document.getElementById('g-recaptcha-response')..setAttribute("value", token);‏

</script>
<script type="text/javascript">
window.onload=function(){ 
    window.setTimeout(document.myform.submit.bind(document.myform), 100);
};
 </script>