Using a link to submit form in jQuery won't wo

2019-07-17 07:44发布

问题:

I have a small form and a link which submits this form using jQuery and POST. I wish to display the HTML output from the process page on the form page without refreshing using AJAX. However, my code doesn't seem to work when I click my submit link. Please can someone point out what I may be doing wrong here? Many thanks.

Regards

<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js">

</script>
    <script type="text/javascript">
        $(document).ready(function(){
            $('#myform').submit(function() {
                $.post('demoprocess.php', $("#myform").serialize(), function(data) {
                    $('#results').html(data);
                });
            });
});
    </script>

<form name="myform" id="myform" action="" method="POST">  
    <label for="name" id="name_label">Name</label>  
    <input type="text" name="name" id="name" size="30" value=""/><br>>

    <label for="email" id="email_label">Email</label>  
    <input type="text" name="email" id="email" size="30" value=""/><br>

    <a href="#" title="" class="pay-button" style="margin-top:5px;" onclick="document.myform.submit()">SUBMIT</a> 
</form>

<!-- We will output the results from demoprocess.php here -->
<div id="results"><div>

回答1:

The trouble is that you are binding a jQuery submit handler but firing the native DOM submit method. This does not fire a submit event, so the jQuery handler is never notified.

You should trigger the event with jQuery instead. It's probably also easiest to do this in jQuery, rather than using an onclick attribute:

$('.pay-button').click(function(e) {
    e.preventDefault(); // prevent the link's default behaviour
    $('#myForm').submit(); // trigget the submit handler
});

Note that this isn't very good design, IMO, because users without Javascript will not be able to submit your form.



回答2:

The problem is that your form doesn't contain any element that fires the javascript submit event

From jquery Documentation .submit():

The submit event is sent to an element when the user is attempting to submit a form. It can only be attached to elements. Forms can be submitted either by clicking an explicit <input type="submit">, <input type="image">, or <button type="submit">, or by pressing Enter when certain form elements have focus.

So, in order to make .submit() works you need to add one of:

  • <input type="submit">,
  • <input type="image">,
  • or <button type="submit">.

    to your form, so you will need to add something like:

    <input type="submit" />
    


回答3:

You can do:

document.forms[0].submit()

or

$('#myform').submit();


回答4:

Try preventing the default behaviour on form submission:

$('#myform').submit(function(ev){
    ev.preventDefault();
    $.post('demoprocess.php', $("#myform").serialize(), function(data) {
        $('#results').html(data);
    });
});