【发布时间】:2020-07-13 17:21:07
【问题描述】:
我正在尝试在博客项目中实现相似的功能。最初,页面使用 html 中的 Jinja2 模板变量显示数据。当用户点击“LIKE”链接时,它会调用一个 javascript 函数,其中 fetch 函数会更新后端的数据并获取最新的点赞数和点赞状态,并在 html 中更新该数据。
问题: JavaScript 工作正常,我可以看到执行 onClick 函数后,点赞数增加,并且锚标记的值从“Like”变为“Unlike”。但是在它被设置为不同之后不久,它就会被 jinja 数据覆盖为“喜欢”。我不确定我在这里缺少什么,非常感谢任何帮助。
HTML 代码:
```<div class="media-body">
<div id="post{{post.id}}">
<h4><a class="article-title" href="{% url 'getProfile' post.get_userId %}">{{ post.user.username }}</a></h4>
<div id='existing-post'>
<p class="article-content">{{ post.content }}</p>
<div class="article-metadata">
<small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small>
<a href="">edit</a>
<input type="hidden" class="hidden" id="userId" value={{user.id}}>
</div>
<i class="fa fa-heart" aria-hidden="true" style="color: red;"></i><span id="countEle"> {{ post.get_likes_count }}</span>
<a href="" class="post{{post.id}}" onclick=changeLikes(this.className) > {% if user in post.get_likes %} Unlike {% else %} Like {% endif%}</a>
</div>
</div>```
JavaScript 代码:
function changeLikes(clickedId){
divEle=document.getElementById(clickedId);
likedBy= document.getElementById('userId').value;
// id_value=this.id
var likedBy =divEle.querySelector('#userId').value;
postId=clickedId.substring(4)
fetch('/changeLikes', {
method: 'POST',
body: JSON.stringify({
'postId': postId,
'likedBy': likedBy
})
})
.then(response => response.json())
.then(result => {
// Print result
console.log(result);
divEle.querySelector('#countEle').textContent=result.likesCount;
divEle.getElementsByClassName(clickedId)[0].textContent=result.likedStatus;
});
}
【问题讨论】:
标签: javascript python-3.x django jinja2