How do you override an existing html form to use jquery to post the form?

前端 未结 3 1855
孤独总比滥情好
孤独总比滥情好 2021-02-05 13:23

I have a simple form that I am currently posting back to the server to update a nickname. What jquery code do I add (without changing the form) so that the page will not refresh

相关标签:
3条回答
  • 2021-02-05 13:46

    There's a plugin just for this.

    http://jquery.malsup.com/form/

    0 讨论(0)
  • 2021-02-05 14:05

    try reading this.

    or

    $("form").submit(function(e){
        var form = $(this);
        $.ajax({ 
             url   : form.attr('action'),
             type  : form.attr('method'),
             data  : form.serialize(), // data to be submitted
             success: function(response){
                alert(response); // do what you like with the response
             }
        });
        return false;
     });
    
    0 讨论(0)
  • 2021-02-05 14:07

    You need to use jQuery to bind to the "submit" event and prevent the default action. It would be a little more efficient if your form and nickname input used id's in addition to their names:

    <script type="text/javascript">
        jQuery(function($){
          $("form[name=input]").submit(function(e){
            e.preventDefault(); // Keep the form from submitting
            var form = $(this);
    
            // Use the POST method to post to the same url as
            // the real form, passing in newNickname as the only 
            // data content
            $.post( form.attr('action'), { newNickname: form.find(':text').val() }, function(data){
              alert(data); // Alert the return from the server
            }, "text" );
          });
        });
    </script>
    
    0 讨论(0)
提交回复
热议问题