javascript - 如何使用 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>
<% } %>
解决方案
在 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");
});
推荐阅读
- laravel-5 - 不能将 stdClass 类型的对象用作数组(查看:
- regex - 正则表达式:如何匹配所有字符,直到下一次匹配?
- python - 如何散列 csv 文件中的特定列?
- eclipse - 当我从“安装新软件”将 javafx 添加到 Eclipse 时
- laravel - laravel 5.5 不支持 jwt auth lib
- html - 悬停时的按钮边框将文本移动到里面
- python - 如何在 jupyter-notebook 中打印字典?
- vue.js - 跟踪 Vue.js 中的子状态变化
- php - 如何从其他方法调用所有变量并在同一视图中返回它
- python - 当墙壁是一组并且我的精灵在另一组时如何实现墙壁碰撞