【问题标题】:Clear form inputs after Posting to MongoDB发布到 MongoDB 后清除表单输入
【发布时间】:2020-09-16 00:40:38
【问题描述】:

我创建了一个将数据发布到 MongoDB 数据库的表单。问题是,当我发布时,我希望刷新输入字段而不必刷新整个页面。

当我调用函数 resetBooks() 时,我认为它会先清除表单,然后再发布任何内容,对吗?

如何获取表单来发布数据,然后清除输入字段。

<div class="booksInput">
  <h4>Add a book</h4>

  <form id="bookForm" method="post" action="/books" 
      target="hiddenFrame" onsubmit="resetBooks()">
       <input class="form-control" name="title" type="text" placeholder="book title">
       <input class="form-control" name="author" type="text" placeholder="author">
       <input class="form-control" name="description" type="text" placeholder="short description">
       <button class="btn btn-primary" type="submit" value="Add Book">Submit</button>
  </form>

</div>

<script>
  function resetBooks(){
    document.getElementById('bookForm').reset();
    };

  app.post("/", (req, res)=>{
  let myBook = new Book (req.body);
  myBook.save()
  .then(item =>{
    res.send("Book saved to database");
  })
  .catch(err=>{
    res.status(err).send("unable to save to database");
   });
  });

</script>

【问题讨论】:

  • 我应该提到 resetBooks() 函数和 app.post() 是在单独的 js 文件中。我不确定这是否会有所不同。

标签: javascript mongodb forms reset


【解决方案1】:

如果您添加一个适用于大多数现代浏览器的任意时间偏移量。以前只有 Chrome 有这个问题,但我知道 FireFox 现在也有。由于新的 Edge 是基于 Chromium 的,我认为您会遇到类似的问题而不会产生影响。

我附上了一些来自 Firefox 请求的屏幕截图,因为小提琴对于表单提交来说太可怕了。

function resetBooks(){
    setTimeout(function(){ document.getElementById('bookForm').reset();}, 100);    
};

【讨论】:

  • 有效!非常感谢这个真的让我很着迷。
  • 这是一种奇怪的解决方法。表单提交通常会强制重定向浏览器,因此表单本身“已消失”,但由于它在不同的窗口中被重定向,而在您的场景中并非如此。如果您将来尝试类似的事情,您可能想要查看 JQuery/Ajax 表单提交。但我完全赞成减少对库的依赖。
猜你喜欢
  • 2016-10-23
  • 2011-10-21
  • 2018-03-14
  • 1970-01-01
  • 2011-11-01
  • 2018-09-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多