Django:更新页面信息而不刷新

2024-04-28 07:27:33 发布

您现在位置:Python中文网/ 问答频道 /正文

每当按下按钮时,我都会尝试更新网站的这一部分:

Coins

在我的模板中,我通过{{ request.user.profile.coins }}访问此信息:

<span class="status">Balance:&nbsp;{{ request.user.profile.coins }}
  <img class="coin-img" src="{% static 'assets/coin.png' %}" height="40px" width="auto">
</span>

我正在研究这个过程,并试图使用AJAX函数调用此视图:

@login_required(login_url='users/login')

def coin_increase(request):
    """
    Function based view for increasing a user's coin balance
    """
    if request.is_ajax():
        try:
            user = request.user
        except User.DoesNotExist:
            raise Http404("No user matches the given query.")
        user.profile.coins += 5
        user.save()
        return render(request, 'home.html', {'home': home})
    else:
        raise Http404

AJAX函数如下:

function update_coins() {
    $.ajax({
      method: "POST",
      url: "/coins",
      data: {},
      success: function(data) {
        alert("test");
      }
    })
  };

我怎样才能让它工作?


Tags: urlhomeimgrequestloginajaxprofileclass
1条回答
网友
1楼 · 发布于 2024-04-28 07:27:33

我猜home.html是整个页面的模板,其中包含感兴趣的部分。

问题在于:

return render(request, 'home.html', {'home': home})

您不需要呈现整个页面来更新该部分。您只需要知道user.profile.coins的新值。 最常用的技术是将数据序列化为javascript可以理解的格式:JSON。

不确定你的django版本是什么,也许这会起作用:

from django.http import JsonResponse
return JsonResponse({'coins':user.profile.coins})

然后:

function update_coins() {
    $.ajax({
      method: "POST",
      url: "/coins",
      data: {},
      success: function(data) {
        console.log(data) // check out how data is structured

        // Update the coin amount
        $('.status').contents()[0].textContent = 'Balance&nbsp'+data.coins
      }
    })
  };

相关问题 更多 >