如何使用djang只呈现部分html数据

2024-07-05 15:03:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用ajax对来自搜索结果的数据进行排序。

现在我想知道是否可以只呈现html的一部分,以便我可以这样加载:

$('#result').html(' ').load('/sort/?sortid=' + sortid);

我这样做,但我得到整个html页面作为响应,它是附加整个html页面到现有的页面,这是可怕的。

这是我的观点.py

def sort(request):
  sortid = request.GET.get('sortid')
  ratings = Bewertung.objects.order_by(sortid)
  locations = Location.objects.filter(locations_bewertung__in=ratings)
  return render_to_response('result-page.html',{'locs':locations},context_instance=RequestContext(request))

如何从视图函数中仅呈现该<div id="result"> </div>?或者我做错什么了?


Tags: 数据divobjects排序requesthtmlloadajax
1条回答
网友
1楼 · 发布于 2024-07-05 15:03:02

据我所知,如果收到ajax请求,您希望以不同的方式处理同一视图。 我建议将您的result-page.html分成两个模板,一个只包含您想要的div,另一个包含所有其他内容并包含另一个模板(请参见django's include tag)。

在您的视图中,您可以执行以下操作:

def sort(request):
    sortid = request.GET.get('sortid')
    ratings = Bewertung.objects.order_by(sortid)
    locations = Location.objects.filter(locations_bewertung__in=ratings)
    if request.is_ajax():
        template = 'partial-results.html'
    else:
        template = 'result-page.html'
    return render_to_response(template,   {'locs':locations},context_instance=RequestContext(request))

结果页面.html:

<html>
   <div> blah blah</div>
   <div id="results">
       {% include "partial-results.html" %}
   </div>
   <div> some more stuff </div>
</html>

部分结果.html:

{% for location in locs %}
    {{ location }}
{% endfor %}

相关问题 更多 >