weixin_33674437 2019-08-21 21:57 采纳率: 0%
浏览 39

AJAX形式部分起作用

I can submit a form like this and it works:

$(document).on('click', '#someLink', function() {
  var frm = $('#myCustomForm');
  frm.submit();
});

However, when I submit the same form like below, the form is not being submitted:

$(document).on('click', '#someLink', function() {
  var frm = $('#myCustomForm');
  frm.submit(function(e) {
    $.ajax({
      type: 'POST',
      url: '/comments/new/',
      dataType: 'application/json',
      data: frm.serialize(),
      success: function(data) {
        alert('successful');
      },
      error: function(data) {
        alert('something went wrong');
      }
    });
    e.preventDefault();
    return false;
  });
});

What am I doing wrong here?

  • 写回答

2条回答 默认 最新

  • 撒拉嘿哟木头 2019-08-21 22:20
    关注

    The two codes are complete opposites. frm.submit(function(e) {}) assigns a function to the form submission so you would need to submit the form again.

    You just want to run the Ajax code so just run the code.

    $(document).on('click', '#someLink', function(e) {
      var frm = $('#myCustomForm');
      $.ajax({
          ...
      });
      e.preventDefault();
    });
    
    评论

报告相同问题?