【问题标题】:Returning Rendered Html via Ajax通过 Ajax 返回渲染的 Html
【发布时间】:2013-09-29 08:32:28
【问题描述】:

我正在尝试通过 Ajax 调用返回 html,并且我的视图中有以下 sn-p 代码

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

我做错了什么?

【问题讨论】:

    标签: django


    【解决方案1】:

    您的代码存在一些问题:

    您需要使用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)
    

    在你的前端,你需要:

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

    【讨论】:

    • 我收到一个错误,通过 ajax 页面上没有显示任何内容,我使用 jquery 警报打印了错误,我看到以下消息“SyntaxError: Unexpected token
    • 如果 AJAX 调用返回 HTML,诀窍是使用 $('#result').html(data) 而不是 $('#result').text(data)(注意 .html 而不是 .text)。
    • @jabba 使用 .html() 标签替换 div 的问题是你需要先选择父 div 来替换里面的相同内容。更好的技术是使用 .replaceWith
    【解决方案2】:

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

    您可以添加请求对象或改用 Context 类。

    【讨论】:

      【解决方案3】:

      RequestContext() 的第一个参数应该是request,因此将代码中的行更新为

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-05-01
        • 2021-04-25
        • 1970-01-01
        • 2015-04-30
        • 1970-01-01
        • 1970-01-01
        • 2014-04-12
        相关资源
        最近更新 更多