Mongoose に isReviewed という名前の変数を持つポスト スキーマがあります。 unreviewedposts.ejs ファイル内にボタンがあり、クリックすると isReviewed = true になるため、クリック イベント リスナーを含むスクリプトを使用しましたが、クリックしても何も起こりません。
ルートに対して AJAX リクエストを使用すると、変数の値を簡単に変更できることはわかっていますが、変数の値を変更するためだけにリクエストを行うのはオーバーヘッドではないでしょうか?
このスクリプト内の変数のみを更新したいのですが、どうすればよいでしょうか?
ルートの取得:-
router.get('/unreviewedposts', middleware.isAdmin, middleware.isAuditor, (req,res)=>{
Post.find({}, (err,allposts)=>{
if(err) console.log(err)
else{
res.render("unreviewedposts", {posts: allposts})
}
})
})
unreviewedposts.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>unreviewed posts of all the subjects are here </h1>
<% if(currentUser !== null && currentUser.role === "admin" || currentUser.role === "auditor"){ %>
<p><%=currentUser.username%> with <%=currentUser.role%> role is logged in!</p>
<br><br><br>
<% posts.forEach((post)=>{ %>
<h1> <%=post.title%> </h1>
<h3> <%=post.publishDay%> <%=post.publish_date%> </h3>
<h3>published by <%=post.author.username%></h3>
<h4>this post is of <%=post.subject%></h4>
<p><%-post.sanitizedHtml%> </p>
<div>
<span>Likes: <%=post.likes%></span>
<span>Views: <%=post.views%></span>
</div>
<button id="approve">approve this post and send to respective posts page</button>
<script>
var approveButton = document.getElementById('approve');
approveButton.addEventListener('click', ()=>{
<%=post.isReviewed%> = true;
console.log(<%=post.isReviewed%>);
})
</script>
<!-- here we put the operations on these posts by th admins or auditors -->
<a href="/posts/<%=post._id%>/edit">Edit this post</a>
<form action="/<%=post._id%>?_method=DELETE" method="POST">
<button type="submit">Delete post</button>
</form>
<br><br><br><br><br>
<% }) %>
<% } %>
</body>
</html>
------------------------
p を作成したい場合は、データへの永続的な変更は POST する必要があります。そうでない場合、isReviewed への変更はローカル ユーザーのブラウザ内にのみ存在し、他のユーザーには決して表示されず、ページをリロードまたは離れると失われます。オーバーヘッドについてはあまり心配しないでください。データの更新にまさにこのメソッドを使用するのが非常に一般的です。
実際のコードに関しては、post.isReviewed がブール値であると仮定すると、次の行は実行できません。
<%=post.isReviewed%> = true;
これは次のようにレンダリングされるためです。
true = true;
または:
false = true;
これは明らかに無効です。
代わりに、次のようなことを行う必要があります:
let postIsReviewed = <%=post.isReviewed%>;
その後、イベント ハンドラーでその変数を変更します。