【问题标题】:Django: Update Page Information Without RefreshingDjango:更新页面信息而不刷新
【发布时间】:2017-05-29 21:41:41
【问题描述】:

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

在我的模板中,我通过{{ 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");
      }
    })
  };

我怎样才能让它工作?

【问题讨论】:

  • 如果您在更新 DOM 内容时遇到问题,也请放入您的模板 html 代码。

标签: jquery python ajax django database


【解决方案1】:

我猜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
      }
    })
  };

【讨论】:

  • 我在控制台中得到Object { coins: 6725 }
  • 好 :) 现在,使用 jquery 选择包含硬币数量的 DOM 元素并使用data.coins 更新它。如果您不熟悉 jquery 选择器,请发布您的 html,我会帮助您
  • 我的 HTML 看起来像:` 余额: {{ request.user.profile.coins }}`, 所以我应该做 $( ".status" ).something(data.coins)?
  • 使用$('.status').contents()[0].textContent = 'Balance&amp;nbsp'+data.coins。请参阅stackoverflow.com/questions/9956388/… 了解更多信息
  • 对我来说不起作用:这里我有一些问题:stackoverflow.com/questions/58060402/…
猜你喜欢
  • 2016-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-28
  • 2021-07-24
  • 2013-07-24
  • 2011-12-22
相关资源
最近更新 更多