Django Ajax更新Div而不刷新

Django Ajax Update Div without Refresh

本文关键字:刷新 Div Ajax 更新 Django      更新时间:2023-09-26

我正在尝试在不刷新页面的情况下更新<strong id="vote_count">。目前,ajax请求已经发布,但我必须手动刷新页面以更新投票计数。CCD_ 2最初是CCD_ 3模型中的一个函数。

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();
    });
});

视图.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)

models.py(编辑):

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)

感谢您提供的所有疑难解答。我能够通过更改来解决这个问题

$('#vote_count').html(data);
$('#upvotes').hide();

$('.vote_count').html(data);
$('.upvotes').hide();

并且在html中使用class而不是id标记。仍然不确定为什么id标签不起作用。