【问题标题】:EJS - Updating data in my database without reloading the page from EJSEJS - 在我的数据库中更新数据而不从 EJS 重新加载页面
【发布时间】:2018-08-29 03:22:35
【问题描述】:

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

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

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

快递代码:

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 应该写什么)

【问题讨论】:

    标签: javascript node.js express ejs


    【解决方案1】:

    酷。所以 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 写什么……请记住,您可以自己弥补。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-23
      • 1970-01-01
      • 1970-01-01
      • 2013-09-10
      • 2020-05-20
      • 2019-05-28
      相关资源
      最近更新 更多