javascript - Jquery $(this).closest ('form' );单击按钮后不工作

标签 javascript jquery ajax

我有以下js代码:

$("#add_station").on('click', function () {

   $(this).closest('form').submit(function () {
      alert("working!");
      $.ajax({
         url: advoke.base_url + "/new-vendor-user/station/ajax",
         method: 'post',
         processData: false,
         contentType: false,
         cache: false,
         dataType: 'json',
         data: new FormData(this),
         beforeSend: function () {

            $('.info').hide().find('ul').empty();

            $('.success_message').hide().find('ul').empty();

            $('.db_error').hide().find('ul').empty();
         },
         success: function (data) {

            if (!data.success) {

               $.each(data.error, function (index, val) {

                  $('.info').find('ul').append('<li>' + val + '</li>');

               });

               $('.info').slideDown();
               setTimeout(function () {
                  $(".info").hide();
               }, 5000);

            } else {
               $('.success_message').slideDown();
               $('#add_station').remove();
               $("#station").append(data.new_station);
               setTimeout(function () {
                  $(".success_message").hide();
               }, 5000);

            } //success

         },
         error: function () {

            //db error
            $('.db_error').append('<li>Something went wrong, please try again!</li>');
            $('.db_error').slideDown();
            //Hide error message after 5 seconds
            setTimeout(function () {
               $(".db_error").hide();
            }, 5000);

         } //error
      });
   });
   return false;
});

当我单击 ID 为 add_station 的按钮时,它会在 $($this).closest('form').submit(function(){... ) 它不起作用,正如你所看到的,我在提交函数之后放置了一个“起作用”的警报。我在控制台上没有收到任何错误,我不知道问题是什么。此外,单击的按钮位于表单内。

我需要在里面使用 $($this).closest('form').submit(function(){...) 因为ajax成功后将使用 add 生成一个新表单将使用此代码的车站按钮。

最佳答案

您应该使用阻止默认提交触发器

e.preventDefault();

$(this).closest('form').submit(function (e) {

e.preventDefault();

<!--rest of the code-->

})

关于javascript - Jquery $(this).closest ('form' );单击按钮后不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26846252/

相关文章:

javascript - 如何解释 vue.js 中 console.log() 的这种奇怪行为?

javascript - 如何在 v-time-picker 中禁用选择分钟?

javascript - innerHTML 和事件委托(delegate)

javascript - 从 iframe 访问父窗口的元素

javascript - 如何使用ajax从div id中提取数据?

javascript - React - 按对象属性过滤

javascript - jQuery 去掉数组中的空格

javascript - 通过AJAX、PHP获取值

javascript - 如何从之前选择的 radio 中获取值?

php - AJAX:如何尽可能高效地显示/添加/编辑/删除(CRUD)?