我不知道为什么我的Ajax无法与Django一起使用(如按钮)

时间:2018-09-06 18:43:04

标签: javascript ajax django django-rest-framework django-views

我想用我的Django项目实现我的Ajax,这意味着我不希望用户在单击按钮后看到重新加载的页面。

但是出了点问题,我的ajax显示了不正确的点赞次数。例如,如果我有3个顶,然后添加另一个顶,它将显示4个顶,但是当我再次单击时,它将显示2个顶。出了什么问题,我该如何预防?

这是我所有的文件: views.py

class PostLikeAPIToggle(APIView):
    authentication_classes = (authentication.SessionAuthentication, )
    permission_classes = (permissions.IsAuthenticated,)

    def get(self, request, slug=None, format=None):
        #slug = self.kwargs.get("slug")
        post = get_object_or_404(Post, slug=slug)
        user = self.request.user
        updated = False
        liked = False
        if user.is_authenticated:
            if user in post.likes.all():
                liked = False
                post.likes.remove(user)
            else:
                liked = True
                post.likes.add(user)
            updated = True
        data = {"updated": updated,"liked": liked}
        return Response(data)

我的AJAX(或JavaScript)

<script type="text/javascript">
    $(document).ready(function(){

function Updating(btn, newCount, verb){
btn.text(newCount + " " + verb)
}
$(".like-btn").click(function(e){
    e.preventDefault()
    var this_ = $(this)
    var likeUrl = this_.attr("data-href")
    var likeCount = parseInt(this_.attr("data-likes"))
    var addLike = likeCount + 1
    var removeLike = likeCount - 1
    $.ajax({
        url:likeUrl,
        method: "GET",
        data: {},
        success: function(data){
            console.log(data)
            if (data.liked){
                Updating(this_, "", addLike)
            } else {
                Updating(this_, "", removeLike)
            }
        }, error: function(error){
            console.log(error)
            console.log("error")
        }
    })
})
})
</script>

还有我的HTML文件

    <div style="margin: 15px 150px 15px 20px; font-size: 35px; display: block">
        {% if request.user in post.likes.all %}
        <a data-likes="{{ post.likes.count }}" class="like-btn"  href="{% url 'forum:like_post_like' slug=post.slug %}" data-href="{% url 'forum:like_post_like' slug=post.slug %}"><i class="fas fa-heart"></i> {{ post.likes.count }}</a>
        {% else %}
        <a data-likes="{{ post.likes.count }}" class="like-btn" href="{% url 'forum:like_post_like' slug=post.slug %}" data-href="{% url 'forum:like_post_like' slug=post.slug %}"><i class="far fa-heart"></i> {{ post.likes.count }}</a>
        {% endif %}
    </div>

0 个答案:

没有答案