Ajax防止默认并在当前页面上提交表单

时间:2016-11-13 16:38:06

标签: javascript jquery ajax

我有以下脚本,它完美地工作但是问题是我需要一个form action attribute才能工作,因此我的问题是如何修改我当前的脚本以防止默认表单提交行为和在当前页面上提交表单,而无需表单中的action attribute

$(function() {
  var form = $('#editRes');
  var formMessages = $('#formMsg');
  // Set up an event listener for the contact form.
  $(form).submit(function(e) {
    // Stop the browser from submitting the form.
    e.preventDefault();
    //do the validation here
    if (!validateLog()) {
      return;
    }
    // Serialize the form data.
    var formData = $(form).serialize();
    // Submit the form using AJAX.
    $.ajax({
      type: 'POST',
      url: $(form).attr('action'),
      data: formData
    }).done(function(response) {
      // Make sure that the formMessages div has the 'success' class.
      $(formMessages).removeClass('error').addClass('success');
      // Set the message text.
      $(formMessages).html(response); // < html();
      // Clear the form.
      $('').val('')
    }).fail(function(data) {
      // Make sure that the formMessages div has the 'error' class.
      $(formMessages).removeClass('success').addClass('error');
      // Set the message text.
      var messageHtml = data.responseText !== '' ? data.responseText : 'Oops! An error occured!.';
      $(formMessages).html(messageHtml); // < html()
    });

  });
  function validateLog() {
    var valid = true;
    //VALIDATE HERE
    return valid;
  }
})

3 个答案:

答案 0 :(得分:0)

在您的ajax中,您正在使用url: $(form).attr('action')。这意味着表单将提交给表单的action属性。由于没有,ajax将无效。

如果您希望表单没有action标记,则可以在ajax网址部分中编写表单提交网址( page.php

$.ajax({
    type: 'POST',
    url: 'page.php',
    data: formData,
    ...
    ...
});

答案 1 :(得分:0)

另一种选择是return new GitHubApp();

附注:您不需要在window.location.href中重新包装form,因为它已经是第二行中的jQuery对象 - $()也是如此。

formMessages

答案 2 :(得分:0)

在提交功能结束时添加:

return false;

这将阻止浏览器导航。

相关问题