gpt4 book ai didi

javascript - EJS - 更新数据库中的数据,无需从 EJS 重新加载页面

转载 作者:行者123 更新时间:2023-12-01 02:18:23 25 4
gpt4 key购买 nike

我正在创建类似 reddit 评论部分的内容,有人可以评论某些内容,人们也可以回复该评论。

我正在使用 Node、Express、MySQL、EJS。

问题:我不知道如何制作赞成/反对部分,我不知道如何制作一个 onclick 事件,该事件将告诉我的数据库在不重新加载页面的情况下对该评论投赞成票/反对票 1。

express 代码:

app.get("/posts", function(req,res){
connection.query(`SELECT post FROM testingposts`, function(error,result){
if(error){
console.log(`error 757`)
} else {
console.log(`works btw`)
res.render("posts", {result: result })

}
})
})



app.post("/posts", function(req,res){
let post = req.body.post;
console.log(`req.body`)
console.log(req.body.theValue)

connection.query(`INSERT INTO testingposts(post) VALUES(?)`, [req.body.post], function(error,result){
if(error){
console.log(`error 555`)
} else {

res.redirect("/posts")

}
})
})

EJS:

//This part basically creates the html elements for the comments. 
//But I haven't added the upvote/downvote elements yet.
<% for(let i = 0; i < result.length; i++){ %>
<div value="<%= i %>">
<p><%= result[i].post %></p>
<input id="<%= i %>" type="submit" value="reply" onclick=bob(event) >
<input type="submit" value="report" >
</div>


<form method="post" action="posts" style="display:none">

<textarea name="replytextarea" id="" cols="30" rows="10"></textarea>
<input type="text" class="forValue" name="theValue" value="5" style="display: none">
<input type="submit" value="submit btw" onclick="setValue(event)">
</form>

<% } %>

我尝试用 Fetch 尝试一些东西,但它对我来说不能正常工作。(我不知道该写什么作为 URL)

最佳答案

酷。因此,express 的优点之一就是你可以创建任何你想要的端点,它会做你想做的任何事情。假设您想要发出一个 AJAX 请求来对某个评论进行投票?您可以创建它。

(这些是 PUT 路由,因为它们更改有关已存在记录的信息。)

router.put('/posts/upvote/:comment_id', (req, res) => {
// something that increments the number of upvotes for that particular comment
res.status(200).json({voteNum: // new vote number})
})

router.put('/posts/downvote/:comment_id, (req, res) => {
// something that decrements the number of downvotes for that particular comment
res.status(200).json({voteNum: // new vote number})
})

然后你就可以使用它了:

// when the upvote button is clicked
fetch(`/posts/upvote/${your_comment_id}`, { method: 'PUT', credentials: 'include' })
.then(res => res.json())
.then(jsonRes => {
// get the element with the number of votes
element.innerText = jsonRes.voteNum
})

当然,这需要一些工作才能将其融入您的代码中。但是,总的来说,如果您不确定要为 URL 写什么...请记住,您可以弥补。

关于javascript - EJS - 更新数据库中的数据,无需从 EJS 重新加载页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49382068/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com