首页 > 解决方案 > 如何使用 Node/Express 和 HTML 表单按 ID 删除许多项目

问题描述

我有一个“通知”系统,我可以使用 html 上的按钮一一删除每个通知。但是,我想使用“全部清除”按钮删除许多通知,但我不是我尝试过的不同策略不起作用的原因。

我已经尝试在 HTML 中放置一个 for 循环来发布要删除的整个通知数组,但这对我不起作用。

我还尝试放入 app.post("/notification/delete/all")... Notification[] 或清除数组的东西,但我不知道我做错了什么。

我从下面的代码中删除了我尝试过的策略,也许我的初始设置有问题。

app.post("/notification/delete/:id", async (req, res) => {
   const result = await Notification.findByIdAndDelete(req.params.id);
   res.redirect("back");
 });

 app.post("/notification/delete/all", async (req, res) => {
   res.redirect("back");
 });
<form action="/notification/delete/all" method="post">
   <button id="clear">Clear All</button>
</form>
</h6>


<% for (var i = 0; i<notification.length; i++) {%>
  <a class="dropdown-item d-flex align-items-center" href="#">
     <div class="mr-3">
     <div class="icon-circle bg-primary">
     <i class="fas fa-file-alt text-white"></i>
     </div>
     </div>

<div>
   <div class="small text-gray-500"><%= notification[i].timeStamp %></div>
 <span class="font-weight-bold"><%= notification[i].details %></span>

      </div>
<form action="/notification/delete/<%- notification[i]._id %>" method="post">
 <button id="clear" value='<%- notification[i]._id %>'>Clear</button>
</form>
</a>

<% } %>

标签: javascripthtmlnode.jsexpress

解决方案


在 delete all 表单中传递所有 id,用逗号分隔,然后在服务器中,拆分 id 并删除项目。

<form action="/notification/delete/all" method="post">
    <input type="hidden" name="ids" value="<%- notification.map(item => item._id).join(',') %>">
    <button id="clear">Clear All</button>
</form>
<% for (var i = 0; i<notification.length; i++) {%>
    <a class="dropdown-item d-flex align-items-center" href="#">
        <div class="mr-3">
            <div class="icon-circle bg-primary">
                <i class="fas fa-file-alt text-white"></i>
            </div>
        </div>
        <div>
            <div class="small text-gray-500"><%= notification[i].timeStamp %></div>
            <span class="font-weight-bold"><%= notification[i].details %></span>
        </div>
        <form action="/notification/delete/<%- notification[i]._id %>" method="post">
            <button id="clear" value='<%- notification[i]._id %>'>Clear</button>
        </form>
    </a>
<% } %>


app.post("/notification/delete/all", async (req, res) => {
    const ids = req.body.ids.split(',');
    for (const id of ids) {
       await Notification.findByIdAndDelete(id);
    }
    res.redirect("back");
});

推荐阅读