用JS编写一个评论区有删除功能
时间: 2023-09-16 14:13:03 浏览: 60
好的,这是一个技术问题,我可以帮您解答。要实现评论区的删除功能,您可以使用Ajax向后端发送请求,删除对应的评论,并在前端刷新页面或删除对应的DOM节点。以下是一个简单的代码示例:
```
// front-end code
function deleteComment(commentId) {
$.ajax({
url: '/api/delete_comment',
data: {
comment_id: commentId
},
success: function(response) {
// remove the deleted comment from DOM
$('#comment-' + commentId).remove();
},
error: function(xhr, status, error) {
alert('Failed to delete the comment.');
}
});
}
// back-end code (using Node.js and Express)
app.post('/api/delete_comment', (req, res) => {
const commentId = req.body.comment_id;
// do the deletion operation
// ...
res.send('Comment deleted successfully.');
});
```
当用户点击删除按钮时,可以调用 `deleteComment` 函数,并传入要删除的评论的ID。该函数向后端发送一个POST请求,并带上要删除的评论的ID。后端接收到请求后,进行对应的删除操作。如果删除成功,后端返回一个成功的响应。前端收到成功响应后,移除相应的DOM节点。