【问题标题】:CS50 Web - Project 4 NetworkCS50 网络 - 项目 4 网络
【发布时间】:2021-12-26 14:05:14
【问题描述】:

我目前正在研究 CS50 Web 项目 4 - 网络。任务是设计一个类似推特的网络。目前,我被困在 Like-Function 中。

我有一个点赞按钮和一个点赞计数器。当我单击赞按钮时,页面上的计数器显示“未定义”。但是当我重新加载页面时,一切都很好,点赞数显示正确的点赞数,点赞按钮也变成了不喜欢的按钮。有谁知道有什么问题?我现在被困了好几天,无法弄清楚。非常感谢任何帮助。

这是我的代码:

views.py

@csrf_exempt
def like(request, post_id):
    post = Post.objects.get(id=post_id)

    if request.method == "GET":
        return HttpResponseRedirect(reverse("index"))

    if request.method == "PUT":
        data = json.loads(request.body)
        if data.get("like"):
            Likes.objects.create(user=request.user, post=post)
            post.likes = Likes.objects.filter(post=post).count()
        else:
            Likes.objects.filter(user=request.user, post=post).delete()
            post.likes = Likes.objects.filter(post=post).count()
        post.save()
        return HttpResponse("done")

java.js

function like(id) {
    fetch(`/like/${id}`, {
        method: 'PUT',
        body: JSON.stringify({
            like: true
        })
    })
    .then(post => {
        document.querySelector(`#like_count${id}`).innerHTML = post.likes;
    });
}

function unlike(id) {
    fetch(`/like/${id}`, {
        method: 'PUT',
        body: JSON.stringify({
            like: false
        })
    })
    .then(post => {
        document.querySelector(`#like_count${id}`).innerHTML = post.likes;
    });
}

在我的 html 上:

<div id="like_count{{post.id}}">Likes: {{ post.likes }}</div>

{% if liked %}
<button class="btn btn-outline-danger" id="unlike_button{{post.id}}" onclick="unlike('{{ post.id }}')">Unlike</button>

{% else %}
<button class="btn btn-outline-primary" id="like_button{{post.id}}" onclick="like('{{ post.id }}')">Like</button>

{% endif %}

【问题讨论】:

    标签: javascript python cs50


    【解决方案1】:
    1. 您的视图只返回"done",而不是具有likes 属性的对象。
      您可能需要 return JSONResponse({"likes": post.likes}) 之类的东西。
    2. fetch() 返回的值是一个响应。 (您正在尝试访问likes。)您需要等待res.json() 才能将JSON 响应解码为对象。 (同时,我们可以删除代码中的一些重复。)
    function likeOrUnlike(id, like) {
      fetch(`/like/${id}`, {
        method: "PUT",
        body: JSON.stringify({ like: !!like }),
      })
        .then((resp) => resp.json())
        .then((post) => {
          document.querySelector(`#like_count${id}`).innerHTML = post.likes;
        });
    }
    
    function like(id) {
      likeOrUnlike(id, true);
    }
    
    function unlike(id) {
      likeOrUnlike(id, false);
    }
    

    【讨论】:

    • 非常感谢!!类似计数现在完美运行。但是当我刷新页面时,like 按钮仍然只会改变。我在我的索引视图中检查帖子是否被喜欢。如何通过 javascript 代码刷新此信息?
    • 在您的页面源代码中同时拥有点赞按钮和不喜欢按钮可能会更容易,但根据事物是否被点赞(使用例如style="display:none")只显示一个。那么在 JavaScript 代码中翻转可见性就很容易了。
    • 再次感谢!我不得不重组一些东西,但现在我在我的 java 脚本中添加了一个 if 语句,以根据值更改样式/可见性
    猜你喜欢
    • 1970-01-01
    • 2011-02-28
    • 2012-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-31
    • 2021-10-20
    • 2018-06-08
    相关资源
    最近更新 更多