Ajax调用获取新的JSON数据以更新Django模板

时间:2016-11-22 05:33:22

标签: javascript jquery json ajax django

我一直在试图找出过去几个小时没有运气的问题。

我希望我的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,我想渲染我的模板的其余部分,或者我想将我作为dom元素获得的JSON渲染到我的页面。

这是我称之为我的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})

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以尝试在视图中呈现模板,然后将其发送回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")
相关问题