【问题标题】:Django - Mix HTML template and queryset in json ajax responseDjango - 在 json ajax 响应中混合 HTML 模板和查询集
【发布时间】:2014-08-04 00:15:31
【问题描述】:

我希望我的视图返回页面内容和一些我想在 Ext.Ajax.request 成功函数中使用的参数。

views.py

def importFile(request):
    form = ImportVectorForm()
    html_response = render_to_response("page_content.html", {'form': form, 'folder':folder, 'nodes':nodes},context_instance=RequestContext(request))
    if request.POST:
        form = ImportVectorForm(request.POST, request.FILES)
        if form.is_valid():
            ## here im dealing with the form...
            object = MyObject.objects.create()
            html_response = render_to_response("page_content.html", {'form': form},context_instance=RequestContext(request))
            json_param = serializers.serialize('json', object)
            return StreamingHttpResponse(html_response, content_type="plain/text")

        else:
            html_response = render_to_response("page_content.html", {'form': form},context_instance=RequestContext(request))

    return StreamingHttpResponse(html_response, content_type="plain/text")

ajax.js:

  importFileAjax = function(node_id){
    Ext.Ajax.request({
      method: "GET",
      form: "importForm",
      url: "/basqui/file/import/" + node_id + "/",
      success: function(r){
                  // here I would like to access the model instance created properties
                  Ext.get('table').update(r.responseText); //this update the page content
               }
    });
  }

我想将 html_responsejson_param 都传递给 Ajax。第一个更新div,第二个访问它的属性。

这样做的正确方法是什么?

如何创建一个 JSON,其中包含作为字符串的 html 模板和模型实例?

【问题讨论】:

    标签: ajax json django


    【解决方案1】:

    首先,使用render_to_string 获取模板片段作为HTML 字符串。其次,将您的对象序列化为 Python 字典,而不是 JSON。然后,您可以一次将全部转换为 JSON。

    html = render_to_string("page_content.html", {'form': form}, context_instance=RequestContext(request))
    param = serializers.serialize('python', object)
    data = json.dumps({'html': html, 'param': param})
    return StreamingHttpResponse(data, content_type="application/json")
    

    现在您的 JS 可以解析 JSON 并访问 htmlparam 值。

    【讨论】:

    • 你给人留下了深刻的印象,非常感谢丹尼尔。
    • 这是一种普遍接受的通过单个 Ajax 请求同时检索 HTML 和数据的方式吗?在其他地方,我看到了执行两个请求的建议——一个用于数据,一个用于 HTML。虽然我当然更喜欢这个建议。
    猜你喜欢
    • 2015-04-28
    • 1970-01-01
    • 1970-01-01
    • 2021-03-31
    • 1970-01-01
    • 1970-01-01
    • 2015-12-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多