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

时间:2017-05-29 21:41:41

标签: jquery python ajax django database

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

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");
      }
    })
  };

我怎样才能让它发挥作用?

1 个答案:

答案 0 :(得分:2)

我想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
      }
    })
  };
相关问题