简体   繁体   English

CS50 网络 - 项目 4 网络

[英]CS50 Web - Project 4 Network

I am currently working on the CS50 Web Project 4 - Network.我目前正在研究 CS50 Web 项目 4 - 网络。 The task is to design a twitter-like Network.任务是设计一个类似推特的网络。 Currently, I am stuck at the Like-Function.目前,我被困在Like-Function。

I have a like-button and a counter of the likes.我有一个赞按钮和一个赞计数器。 When I click the like-button, the counter on the page says "undefined".当我点击喜欢按钮时,页面上的计数器显示“未定义”。 But when I reload the page, everything is fine and the like-count shows the right number of likes and also the like button has changed to an unlike button.但是当我重新加载页面时,一切都很好,喜欢计数显示了正确的喜欢数量,而且喜欢按钮已更改为不同按钮。 Does anyone have an idea what the issues?有谁知道有什么问题? I am stuck for days now and cannot figure it out.我现在被困了好几天,无法弄清楚。 Any help is much appreciated.任何帮助深表感谢。

Here is my code:这是我的代码:

views.py视图.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 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;
    });
}

and on my html:在我的 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 %}
  1. Your view only ever returns "done" , not an object that would have a likes attribute.您的视图只返回"done" ,而不是具有likes属性的对象。
    You may want something like return JSONResponse({"likes": post.likes}) instead.你可能想要类似return JSONResponse({"likes": post.likes})
  2. The value fetch() returns is a Response. fetch()返回的值是一个响应。 (You're trying to access likes on it.) You'll need to await on res.json() to decode a JSON response into an object. (您正在尝试访问likes它。)您需要等待res.json()将 JSON 响应解码为对象。 (While at it, we can remove a bit of repetition in the code.) (同时,我们可以删除代码中的一些重复。)
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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如果我不重新加载页面,为什么我的 js 无法正常工作。 这是用于 CS50 Web 项目 3 - Why does my js work incorrectly if i do not reload the page. This is for CS50 Web Project 3 cs50 src5 示例网页无响应 - cs50 src5 example webpage not responding Javascript模块未出现在通过CS50 IDE托管的网站中 - Javascript module not appearing in website hosted through CS50 IDE pset8; CS50; JavaScript的; 何时使用命名函数以及何时在回调中使用匿名函数 - pset8; cs50; javascript; when to use a named function and when to use an anonymous function in callback 从 Python 创建的数组中填充 HTML 下拉列表 - cs50 Finance - HTML populating dropdown list from array created in Python - cs50 Finance CS50 PSet8混搭-标记不在Google地图上显示 - CS50 PSet8 Mashup - Markers don't show on Google map 根据表单的选定项动态更改表单字段的最大值(CS50 PSET8 Finances) - Dynamic change the max of a form field based on a selected item of the form (CS50 PSET8 Finances) 处理 CS50 琐事。 程序响应错误答案但不正确答案 - Working on cs50 trivia. Program responds to incorrect answer but not correct one 如何更新我的 function 以便无论缩放和视图如何,谷歌地图上总是有 10 个标记(混搭使用 CS50) - How to update my function so that there are always 10 markers on Google Maps regardless of zoom and view (Mashup used CS50) Dreamweaver CS5.5 | Slider Div隐藏50% - Dreamweaver CS5.5 | Slider Div Hide on 50%
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM