preventDefault()不会停止重新加载页面/表单

时间:2019-04-04 06:12:03

标签: jquery ajax

尝试使用preventDefault()停止重新加载页面,但仍在重新加载页面。我以前用过它,而且它也起作用。但是我无法在此代码中找到错误。请帮忙。 TIA。

  

HTML

<form method="post" id="submitform">
Student ID:<br>
<input type="text" name="sid"><br>
First name:<br>
<input type="text" name="firstname"><br>
Last name:<br>
<input type="text" name="lastname"><br>
</form>
  

jquery

  $(function () {
  $('#submitform').on('submit', function (e) {
  e.preventDefault();
  var form = $('#submitform');
  var formData = $(form).serialize);
  $.ajax({
  url: location.pathname,
  method: 'POST',
  type: 'POST',
  data: JSON.stringify(formData),
  processData: false,
  dataType: 'json',
  contentType: 'application/json; charset=utf-8',
  });
 });
}

2 个答案:

答案 0 :(得分:1)

只要清理语法,您的代码就可以正常工作。

$('#submitform').on('submit', function(e) {
  e.preventDefault();
  var form = $('#submitform');
  var formData = $(form).serialize();

  console.log(formData);

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" id="submitform">
  Student ID:<br>
  <input type="text" name="sid"><br> First name:<br>
  <input type="text" name="firstname"><br> Last name:<br>
  <input type="text" name="lastname"><br>
  <input type="submit" />
</form>

答案 1 :(得分:0)

尝试此代码段

  $(document).on('submit', '#submitform', function (e) {
  e.preventDefault();
  var formData = $(this).serialize();
  $.ajax({
  url: location.pathname,
  method: 'POST',
  type: 'POST',
  data: JSON.stringify(formData),
  processData: false,
  dataType: 'json',
  contentType: 'application/json; charset=utf-8',
  });
});