【问题标题】:Ajax call to fetch new JSON data to update Django templateAjax 调用以获取新的 JSON 数据以更新 Django 模板
【发布时间】:2017-04-05 16:35:33
【问题描述】:

过去几个小时我一直试图找出问题所在,但没有成功。

当用户接近底部时,我希望我的 django 模板将新的 json 数据加载到用户的屏幕。基本上我想让我的 django 应用程序在滚动时加载内容。

这就是我增加偏移量以从 api 获取新数据的方式

$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
   alert("Requesting new data");
   offset++;
   $.post('/releases/fetch/', {'offset': offset}, function(data){
        console.log("---")
        console.log(data);
        console.log("---")
   });
 }
});

我确实得到了我想要的新 JSON,所以 ajax 的帖子运行良好并且偏移量增加了。现在有了这个新的 JSON,我想渲染模板的其余部分,或者更确切地说,我想将获得的 JSON 作为 dom 元素渲染到我的页面。

这是我为我的 aja 帖子调用的 django 视图

def ajax_view(request):
if request.is_ajax():
    offset = request.POST['offset']
    games = services.get_games(offset)
    return HttpResponse(games)
return HttpResponse("Get out!! 404")

所以我应该将 django 的渲染称为 HttpResponse 吗?

哦,这是渲染我正在谈论的模板的 django 类视图

class HomePage(TemplateView):
  def get(self, request):
    # Sends the json to the template
    games = services.get_games(0)
    return render(request, 'releases/game_list.html', {"games": games})

谢谢!

【问题讨论】:

  • 你是返回 ajax 还是视图?
  • 为什么不能使用相同的代码?它的作用完全相同。

标签: javascript jquery json ajax django


【解决方案1】:

您可以尝试在视图中渲染模板并将其发送回HttpResponse

from django.template import loader, Context

def ajax_view(request):
    if request.is_ajax():
        offset = request.POST['offset']
        games = services.get_games(offset)
        template = loader.get_template('releases/game_list.html')
        context = {"games": games}
        rendered_content = template.render(context)
        return HttpResponse(rendered_content)
    return HttpResponse("Get out!! 404")

【讨论】:

    猜你喜欢
    • 2019-02-05
    • 2020-08-05
    • 2020-01-18
    • 2016-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 2017-08-14
    相关资源
    最近更新 更多