How to reliably submit an HTML form with JavaScript?

后端 未结 7 1584
面向向阳花
面向向阳花 2020-12-13 20:33

Is there a way to submit an HTML form using JavaScript that is guaranteed to work in all situations?

I elaborate. The common approach seems to be:

fo         


        
相关标签:
7条回答
  • 2020-12-13 21:08

    Create another form in JavaScript, and apply its submit() method on your original form:

    <html>
        <script>
            function hack() {
                var form = document.createElement("form");
                var myForm = document.example;
                form.submit.apply(myForm);
            }
        </script>
    
        <form name="example" id="example" method="get" action="">
            <input type="hidden" value="43" name="hid">
            <button 
              type="button" 
              name="submit" 
              onclick="hack();return false;"
            >Submit</button>
        </form>
    </html>
    

    form.submit is the reference to a fresh and clean submit method, and then you use apply(myForm) to execute it with the original form.

    0 讨论(0)
提交回复
热议问题