用Django模板响应AJAX [英] Respond to AJAX with Django template rendered

查看:193
本文介绍了用Django模板响应AJAX的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够将完全渲染的模板返回给ajax调用.例如:

I want to be able to return fully rendered templates to an ajax call. For example:

segment.html

<div class="swappable_segment" id="{{ id }}">
    {% for object in objects %}
        <li>Some text</li>
    {% endfor %}
</div>

views.py

def f(request):
    return SOMETHING

应该有一个ajax代码,当我按下页面上的一个按钮时,它会将旧的div换成新呈现的div.

There should be ajax code such that when I press a button on a page, it swaps out the old div with a newly rendered div.

我知道如何做AJAX部分,但是我想知道函数f应该返回什么.我认为它应该使用新div的html返回带有JSON的HttpResonse对象,但是我不知道如何实际呈现它.

I know how to do the AJAX part, but I'm wondering what the function f should return. I'm thinking it should return an HttpResonse object with JSON with the html of the new div, but I dont know how to actually render it.

推荐答案

这样的事情如何?

from django.template.loader import render_to_string

def f(request):

    [...] #logic here to get objects_list

    if request.is_ajax():
        html = render_to_string('path/to/your/segment.html', {'objects': objects_list})
        return HttpResponse(html)

文档: https://docs.djangoproject.com/zh-CN/1.7/ref/templates/api/#the-render-to-string-shortcut

这篇关于用Django模板响应AJAX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆