使用 JavaScript 提交帖子表单

Submitting a post form using JavaScript

本文关键字:表单 提交 JavaScript 使用      更新时间:2023-09-26

我想用JavaScript操作替换我的HTML按钮。虽然我需要一个函数来提交表单才能正常工作。

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>reCAPTCHA | Blazzike</title>
        <script src="//code.jquery.com/jquery-1.10.2.js"></script>
        <script src='https://www.google.com/recaptcha/api.js'></script>
        <script> 
            $(function(){
              $("header").load("HTML/header.html"); 
              $("footer").load("HTML/footer.html"); 
            });
        </script>
        <script>
            var submit = function(){
                document.getElementById("rec").submit();
            }
        </script>
        <link rel="stylesheet" type="text/css" href="CSS/style.css">
        <style>
            #submit {
                background: #1a1a1a;
                color: #ffffff;
                font-size: 25px;
                margin: 0px;
                padding: 0.7em;
                border: 0px;
                width: 303px;
                min-width: 250px;
            }
        </style>
    </head>
    <header></header>
    <body>
        <center>
            <form id="rec" method="POST" action="<?php echo $_GET["r"]; ?>">
                <div data-theme="dark" class="g-recaptcha" data-sitekey="<siteKey>" data-callback="submit"></div>
                <input value="Continue" type="submit" id="submit">
            </form>
        </center>
    </body>
    <footer></footer>
</html>

上面的脚本不起作用,因为我认为 JavaScript 无法以这种方式提交帖子表单。任何帮助都可以。

谢谢布拉兹克。

如果您希望用户单击提交按钮,运行Javascript函数并执行一些任务,然后提交表单,您可以使用jQuery执行以下操作。

//First prevent form from submitting on button click
$("#rec").on('submit', function(e) {
    e.preventDefault();
});
//Detect submit button click and perform some actions, then submit form
$("#submit").on('click', function() {
   //Do whatever you want here
   //...
   $("#rec").submit();
});

尝试一些javascript来通过id选择元素。 确保uou将"rec"作为表单jn的id!

document.getElementById("rec").submit();
  1. 关于 getElementById 的文档
  2. 关于提交功能的文档

编辑 1:使用输入类型="按钮"而不是提交。然后使用Matt Elliot片段的第二部分:

//Detect submit button click and perform some actions, then submit form 
$("#submit").on('click', function() { 
    //Do whatever   you want here //... 
    $("#rec").submit(); 
});