Executing a script after a form has been submitted

2019-09-01 01:35发布

问题:

I found, on this site a way to submit a POST form without leaving the page. In that script, they put instructions on how to have a function take place after the form's been submitted. Here's what the script looked like:

$(document).ready(function(){
$form = $('form');
$form.submit(function(){
  $.post($(this).attr('action'), $(this).serialize(), function(response){
  },'json');
  return false;
});
});​

They said, between function(response){ and },'json'); you can specify other JavaScript to take place like alerts etc. after the form's been submitted. I tried

$(document).ready(function(){
$form = $('form');
$form.submit(function(){
  $.post($(this).attr('action'), $(this).serialize(), function(response){
$('form').hide();
  },'json');
  return false;
});
});

Unfortunately, that does not work, can anybody tell me why? I've set up a jsFiddle. Please help. Thanks.

回答1:

Using $.post, the "function(response)" is only called AFTER a successful result, so you have been misinformed about doing work within this function while the server is processing the request.

To continue processing after sending the request to the server, place the $('form').hide() after the $.post call:

$form.submit(function(){
  $.post(
    $(this).attr('action'), $(this).serialize(), 
    function(response){
    }
    ,'json'
  );
  $('form').hide();
  return false;
});


回答2:

Problems:

  1. Set JavaScript variable as form, not $form. Then use it in jQuery as $(form).
  2. The context of $(this).attr('action') is the $.post() callback, not the form. Solution: $(form) instead of $(this).

Solution:

$(document).ready(function(){
    form = $('form');

    $(form).on('submit', function() {
        $.post($(form).attr('action'), $(this).serialize(), function(response) {
            $('form').hide();
        },'json');

        return false;
    });
});


回答3:

Your fiddle worked fine when the form is changed to

<form action="#" method="post">

And the documentation at http://api.jquery.com/jQuery.post/ shows that this is a valid syntax and http://www.johnnycode.com/blog/2010/04/08/jquery-form-serialize-doesnt-post-submit-and-button-values-duh/ is also a running sample. If it's not working at all for you then, as silly as this is, do you have a reference to jQuery in your page?