2015-04-16 93 views
2

我想能够将完全呈现的模板返回到ajax调用。例如:响应AJAX与Django模板呈现

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与新呈现的股利。

我知道如何做的AJAX部分,但我想知道f应该返回什么功能。我想它应该返回一个带有JSON的HttpResonse对象与新的div的html,但我不知道如何实际呈现它。

回答

3

怎么是这样的:

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/en/1.7/ref/templates/api/#the-render-to-string-shortcut

+0

我给它一个尝试。是否有'is_ajax'的文档?我从未在 – marisbest2

+0

之前看到过,请参阅https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpRequest.is_ajax – mishbah