2013-09-24 88 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})