Ajax,Node:表单提交一次,然后再次按下提交,它将再次提交两次,并不断递增

时间:2018-08-08 18:40:48

标签: javascript node.js ajax forms express

我有一个用Pug编写的简单表格。 Ajax,Node和Express处理表单的提交和路由。

在前端,我可以毫无问题地提交表格。但是,如果再次按下提交按钮,它将重新提交两次表单;如果再次按下它,它将重新提交三次(共6次提交),并且将继续递增。我只希望它每次提交一次。我不想每次都重新加载页面。...

感觉像我必须清除/重置ajax查询。有什么想法吗?

节点index.js

router.post('/addalccollection', (req, res, next) => {


 AlcUser.findById(req.session.userId)
 .exec(function (error, user){
   if (error) {
     return next(error);
   } else {


      AlcUser.findOneAndUpdate({email : user.email}, {$push: {alccollections : req.body.alccollectiontitle}}, function(err, alccol) {
        if (err) {
            next(new Error('Cant add'));
        } if (alccol) {

          console.log('Added the collection')
          res.json({success : "Worked Out!", status : 200});
        }

      }) 



    }
  })

});

Ajax Javascript

function addAlcCollectionItem() {

  console.log('add collection');

  $('#addalccollection').submit(function(e){
       e.preventDefault();

       $.ajax({
         type: 'POST',
         datatype: 'json',

         processData: false,
         data: $("#addalccollection").serialize(),
         url: "/addalccollection",
         success: function(response){
           console.log('Added Collection');
           console.log(response);
        if(response.status == 200){
            //window.location = '/dashboard';
        }


         },

     });

       return false;
  });


}

footer.pug

  form(method='post' style='display: inline-block;' id='addalccollection')

      input#alccollectiontitle.animated(type='text', placeholder='Put Collection Name Here', name='alccollectiontitle', style='')

      input#submitButtonAlcCollection.animated(type='submit', value='Add', onclick='addAlcCollectionItem()')

1 个答案:

答案 0 :(得分:0)

从何处调用addAlcCollectionItem?如果调用不止一次,它将多次绑定表单提交。最好是在加载时仅调用一次。尝试

$(document).ready(function () {
  $('#addalccollection').submit(addAlcCollectionItem);
});

function addAlcCollectionItem(e) {
  e.preventDefault();
  console.log('add collection');
  $.ajax({
    type: 'POST',
    datatype: 'json',
    processData: false,
    data: $("#addalccollection").serialize(),
    url: "/addalccollection",
    success: function (response) {
      console.log('Added Collection');
      console.log(response);
      if (response.status == 200) {
        //window.location = '/dashboard';
      }
    }
  });

  return false;
}