3

我有一个表单,当提交时,它会通过通常的方式e.preventDefault()发送一个 ajax 请求。但是,如果这个ajax请求返回某个条件,我希望表单能够正常提交。我如何实现这一目标?

// Submit handler
$(".reserveer_form").submit(function(event){
  event.preventDefault();

  $.ajax({
    url: $(this).attr("action"),
    data: $(this).serialize(),
    success: function(data) {
      if($(".messagered",data).length > 0){
        var errors = $(".messagered",data);
        $(".gegevens").before(errors);
      } else {
          // SUBMIT THE FORM!
      } 
      
    }
  });

})
4

3 回答 3

6

Invoke the native submit method on the form, so that it doesn't trigger the jQuery handler.

$.ajax({
    context: this, // <-- set the context.
    url: $(this).attr("action"),
    data: $(this).serialize(),
    success: function (data) {
        if ($(".messagered", data).length > 0) {
            var errors = $(".messagered", data);
            $(".gegevens").before(errors);
        } else {
            this.submit(); // <-- submit the form
        }
    }
});
于 2012-07-13T14:30:42.537 回答
1

由于您的评论说您更改了表单变量,因此您可以submit通过检查相同的表单变量来启动处理程序。如果它被改变,只是return true。如果不是,请继续使用当前处理程序。

于 2012-07-13T14:28:31.520 回答
-1

You can use the submit() method or forms:

$(".reserveer_form").submit(function(event){
  event.preventDefault();
  var form = this,
      $form = $(form);

  $.ajax({
    url: $form.attr("action"),
    data: $form.serialize(),
    success: function(data) {
      var errors = $(".messagered", data);
      if (errors.length > 0){
        $(".gegevens").before(errors);
      } else {
        form.submit();
      }
    }
  });
})

However, this seems to be a strange ajax request. First, you send the form (serialized, via ajax) to the server, and when the response contains no errors you send it again? The server would process it twice (and act twice, depending on your form). Also, the user does not get a message that his input is already processed - he clicks "submit", and it always takes a time until it is visibly submitted (where he even could change some input).

于 2012-07-13T14:30:24.613 回答