通过Ajax返回呈现的Html

Tik*_*odo 19 django

我试图返回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}))
Run Code Online (Sandbox Code Playgroud)

和我的Ajax

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

它会引发以下错误

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
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

Bur*_*lid 55

您的代码存在一些问题:

你需要使用render_to_string.

您也不需要将HTML转换为json,因为您要直接替换内容.

把所有这些放在一起你有:

from django.template.loader import render_to_string
from django.http import HttpResponse

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

在您的前端,您需要:

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