2013-09-24 166 views
19

我想通过和Ajax调用返回的HTML呈现的HTML和我有下面的代码片段在我看来返回通过Ajax

if request.is_ajax(): 
t = loader.get_template('frontend/scroll.html') 
html = t.render(RequestContext({'dishes': dishes}) 
return HttpResponse(json.dumps({'html': html})) 

和我的Ajax

$.ajax({ 
      type: "POST", 
      url: "/filter_home", 
      data: {'name': 'me', 'csrfmiddlewaretoken': '{{csrf_token}}'}, 
      success : function(data) { 
       $('.row.replace').html(data); 
      } 
    }); 

,并抛出以下错误

Exception Value: 'dict' object has no attribute 'META' 
Exception Location: /opt/bitnami/apps/django/lib/python2.7/sitepackages/django/core/context_processors.py in debug, line 39 

我做错了什么?

回答

48

更新线有你的代码的几个问题:

您需要使用render_to_string

你也不需要将你的HTML转换成json,因为你直接替换了内容。

把所有这些组合起来,你有:

from django.template.loader import render_to_string 

if request.is_ajax(): 
    html = render_to_string('frontend/scroll.html', {'dishes': dishes}) 
    return HttpResponse(html) 

在你的前端,您需要:

$.ajax({ 
     type: "POST", 
     url: "/filter_home", 
     data: {'name': 'me', 'csrfmiddlewaretoken': '{{ csrf_token }}'}, 
     success : function(data) { 
      $('.row.replace').html(data); 
     } 
}); 
+0

我已经得到一个错误,一切都没有露面通过AJAX页面上,我用jquery警报打印错误,我看到下面的消息“SyntaxError:Unexpected token <”。 ajax不能识别html开始标记吗? –

+0

NVM我发现了错误 –

+1

如果AJAX调用返回HTML,诀窍是使用'$('#result').html(data)'而不是'$('#result').text(data)'(注意**'.html' **而不是'.text')。 – Jabba

-1

RequestContext的第一个参数是一个请求对象。

您可以添加请求对象,也可以使用Context类。

-2

RequestContext()第一个参数是request,所以在你的代码

html = t.render(RequestContext(request, {'dishes': dishes})