django API或JavaScript不一致

xwbd5t1u  于 2023-08-08  发布在  Go
关注(0)|答案(1)|浏览(95)

我在我的模板中有一个JS函数,它与fetch命令一起工作,以中继到Django视图。奇怪的是,大多数时候它都像预期的那样,但有时却不是,我不知道为什么。
模板中的JS:

<script>
    if (document.querySelectorAll(".nav-link")[1].innerHTML != "Log In") {
        var like = document.querySelector(".likes");
        var quantity = document.querySelector(".quantity");
        like.addEventListener("click", () => likes())
        function likes () {
            fetch(`/likes/${like.value}`, {
                method: "PUT"});
            if (like.innerHTML.slice(0, 2) != "Un") {
                like.innerHTML = "Unlike &#128148";
            }
            else {
                like.innerHTML = "Like &#10084";
            }
            fetch(`/likes/${like.value}`)
            .then(response => response.json())
            .then(post => {
                console.log(post["liked"]);
                quantity.innerHTML = post["liked"].length;
            });
        }
    }
</script>

字符串
我的观点:

@csrf_exempt
@login_required
def likes(request, id):
    user = User.objects.get(username=request.user)
    try:
        post = Post.objects.get(pk=id)
    except Post.DoesNotExist:
        return JsonResponse({"error": "No such post"}, status=404)
    
    if request.method == "GET":
        return JsonResponse(post.serialize())

    if request.method == "PUT":
        #data = json.loads(request)
        if user not in post.liked.all() and post.poster != user:
            print("adding")
            post.liked.add(user)
            post.save()
        else:
            print("removing")
            post.liked.remove(user)
            post.save()
        return HttpResponse(status=204)


它应该在空列表和包含2的列表之间交替。
x1c 0d1x的数据
然而,你可以看到,虽然它通常工作正常,但它有一个地方有几个“[2]”在一排,有时它也有几个“[]”在一排。
实际上这只是在添加了第二次抓取后才开始的,但我不明白为什么;在此之前,其交替没有问题。

gcxthw6b

gcxthw6b1#

正如@Jared Smith在评论中所说,fetch的顺序没有保证,因为它是异步的,要控制顺序,请使用asyncawait来等待响应的结果,如下所示:

like.addEventListener("click", async () => await likes())
    async function likes () {
        await fetch(`/likes/${like.value}`, {
            method: "PUT"});
        if (like.innerHTML.slice(0, 2) != "Un") {
            like.innerHTML = "Unlike &#128148";
        }
        else {
            like.innerHTML = "Like &#10084";
        }
        await fetch(`/likes/${like.value}`);
        const post = await response.json();
        quantity.innerHTML = post["liked"].length;
    }

字符串

相关问题