You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CS50 Web Project 4 Network点赞功能点击后计数显示undefined求助

修复方案

核心问题

点赞逻辑在服务端执行成功,所以刷新后数据正常,出错的点是前后端数据交互环节:

  1. 服务端处理完点赞请求后,只返回了纯文本done,没有把更新后的点赞数返回给前端
  2. 前端收到fetch响应后没有解析响应内容,直接尝试读取原始响应对象的likes属性,该属性不存在所以显示undefined
  3. 现有逻辑没有处理点赞后按钮的状态切换,所以点击后按钮不会自动变化

代码修改步骤

第一步:修改后端views.py逻辑

将接口返回值改为JsonResponse,把最新点赞数返回给前端:

from django.http import JsonResponse # 没有导入的话先加这句

@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()
        # 替换原来的HttpResponse
        return JsonResponse({"likes": post.likes})

第二步:修改前端JS逻辑

先解析fetch的响应内容,再更新页面计数和按钮状态:

function like(id) {
    fetch(`/like/${id}`, {
        method: 'PUT',
        body: JSON.stringify({
            like: true
        })
    })
    .then(response => response.json()) // 解析服务端返回的JSON数据
    .then(data => {
        // 更新点赞计数
        document.querySelector(`#like_count${id}`).innerHTML = `Likes: ${data.likes}`;
        // 切换按钮显示状态
        document.querySelector(`#like_button${id}`).style.display = 'none';
        document.querySelector(`#unlike_button${id}`).style.display = 'block';
    });
}

function unlike(id) {
    fetch(`/like/${id}`, {
        method: 'PUT',
        body: JSON.stringify({
            like: false
        })
    })
    .then(response => response.json())
    .then(data => {
        document.querySelector(`#like_count${id}`).innerHTML = `Likes: ${data.likes}`;
        document.querySelector(`#unlike_button${id}`).style.display = 'none';
        document.querySelector(`#like_button${id}`).style.display = 'block';
    });
}

第三步:修改HTML模板

两个按钮都渲染,用样式控制初始显示状态,方便JS切换:

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

<button class="btn btn-outline-danger" id="unlike_button{{post.id}}" onclick="unlike('{{ post.id }}')" style="display: {% if liked %}block{% else %}none{% endif %}">Unlike</button>

<button class="btn btn-outline-primary" id="like_button{{post.id}}" onclick="like('{{ post.id }}')" style="display: {% if liked %}none{% else %}block{% endif %}">Like</button>

内容的提问来源于stack exchange,提问作者Nelso

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 03:45:04