我正在尝试更新<strong id="vote_count">
而不刷新页面。目前,ajax请求已发布,但我必须手动刷新页面以更新投票计数。 recommendation.get_total_votes
最初是recommendation
模型中的函数。
HTML
<div id="vote_count">Vote Count: {{ recommendation.get_total_votes }}</div>
<br>
<button class="upvotes" data-recommendation="{{ recommendation.id }}" class="btn btn-primary" type="button">
<span class="glyphicon glyphicon-thumbs-up"></span>
Upvote1
</button>
ajax.js
$(document).on("click", ".upvotes", function(){
console.log('my message');
var recommendationid = $(this).attr("data-recommendation");
$.post('/upvote/', {recommendation_id: recommendationid}, function(data){
console.log('my message1');
$('#vote_count').html(data);
$('#upvotes').hide();
});
});
views.py
@csrf_exempt
@login_required
def upvote(request):
recommendation_id = None
if request.method == 'POST':
recommendation_id = request.POST['recommendation_id']
get_total_votes = 0
if recommendation_id:
recommendation = coremodels.Recommendation.objects.get(id=int(recommendation_id))
user = request.user
recommendation.votes.up(user)
get_total_votes = recommendation.votes.count()
return HttpResponse(get_total_votes)
class Recommendation(models.Model):
topic = models.ForeignKey(Topic)
user = models.ForeignKey(User)
title = models.CharField(max_length=300)
votes = VotableManager()
def get_total_votes(self):
total = self.votes.count()
return int(total)
答案 0 :(得分:0)
感谢所有的麻烦拍摄。我能够通过改变
来解决这个问题$('#vote_count').html(data);
$('#upvotes').hide();
到
$('.vote_count').html(data);
$('.upvotes').hide();
在html中使用class
代替id
标记。仍然不确定为什么id
标签不起作用。