我一直在做一个博客网站,当然你会在上面发布一些东西。我有一个索引.html我有这个:
{% for post in posts %} {% include "blog/featuredpost.html" %} {% endfor %}
我还使用了Django分页。 现在,我想做的是一个喜欢和不喜欢的按钮,这是可重用的,这意味着我可能会希望它在“博客”/featuredpost.html". 所以,我就是这么做的。你知道吗
<div class="row">
<div class="col-sm-5">
<div id="divLikes" class="col-sm-6 bg-success text-center">
Likes: {{ post.likes }}
</div>
<div id="divDislikes" class="col-sm-6 bg-danger text-center text-block">
Dislikes: {{ post.dislikes }}
</div>
</div>
{% if user.is_authenticated %}
<div>
<div class="col-sm-2">
<form id="like_form" action="" method="POST">
{% csrf_token %}
<button id="like_button" type="submit" value="vote" class="btn btn-success btn-sm btn-block">
<span class="glyphicon glyphicon-thumbs-up" aria-hidden="true"></span> Like
</button>
</form>
</div>
<div class="col-sm-2">
<button type="button" class="btn btn-danger btn-sm btn-block">
<span class="glyphicon glyphicon-thumbs-down" aria-hidden="true"></span> Dislike
</button>
</div>
<div class="col-sm-3">
<button type="button" class="btn btn-warning btn-sm btn-block">
<span class="glyphicon glyphicon-comment" aria-hidden="true"></span> Comment
</button>
</div>
</div>
{% endif %}
<script type="text/javascript">
//$('#like_button').click(function(){ });
/* The for cycle sends all the posts id that should appear on the page.
It should send just the one on which the like button is clicked. */
$(document).on('submit', '#like_form', function(event) {
event.preventDefault();
$.ajaxSettings.traditional = true;
$.ajax({
type: 'POST',
url: '{% url "like" %}',
dataType: 'json',
data: {
csrfmiddlewaretoken: '{{ csrf_token }}',
LikeId: {{ post.id }},
},
success: function(response) {
$('#divLikes').load(' #divLikes', function() {
/* It's important to add the space before #divLikes, I don't know why */
$(this).children().unwrap()
})
}
});
}) 你知道吗
你知道吗视图.py你知道吗
def view_like(request):
# AJAX Like Button
if request.user.is_authenticated:
if request.method == 'POST':
likepostId = request.POST.get('LikeId', '')
print(likepostId)
likepost = get_object_or_404(Post, id=likepostId)
print(likepost.title + " has " + str(likepost.likes))
response_data = {}
return JsonResponse(response_data)
else:
raise Http404
return 200
我现在有它,所以它只会打印出某些东西。在首页上,由于AJAX success函数,它实际上只是复制了html/css部分。我如何让like按钮明确地知道我想要一个like在我点击的某个帖子上?因为,就像现在一样,它只是垃圾处理页面上所有其他帖子的id,没有特定的顺序。你知道吗
问题是有一堆具有相同id(
#like_form
和#like_button
)的节点,并向所有节点添加事件。不允许有多个元素具有相同的id
值。 从form
中删除属性id
,将button
的id
更改为class
,并将其值设置为post的id,即:然后将事件挂接到类
.vote_button
,并提交它的值(因此ajax
请求中的data.LikeId
类似于$(event.target).val()
),以确定您投了哪个帖子编辑:
javascript大致如下所示:
相关问题 更多 >
编程相关推荐