【问题标题】:How to pass an HttpResponse and additional data via Ajax in Django如何在 Django 中通过 Ajax 传递 HttpResponse 和其他数据
【发布时间】:2016-11-15 04:40:52
【问题描述】:

我有两个不同的 AJAX 请求要合并。

第一个得到一些 html:

def ajax_get_html(request):
    if request.is_ajax() and request.method == "POST":
        context = {
            ...
        }
        return render(request,"my_app/my_template.html", context)
    else:
        raise Http404

并且是这样使用的:

    $.ajax({
      type: "POST",
      url: ajax_url,
      data: {
        csrfmiddlewaretoken: "{{ csrf_token }}",
      },
      success: function(data){
        $(my_div).html(data);
      }
    });

我的第二个得到了一些数据:

def ajax_get_data(request):
    if request.is_ajax() and request.method == "POST":
        data = {
            "answer": 42,
        }
        json_data = json.dumps(data)
        return HttpResponse(json_data, content_type='application/json')
    else:
        raise Http404

并且是这样使用的:

$.ajax({
    type: "POST",
    url: another_ajax_url,
    data: {
      csrfmiddlewaretoken: "{{ csrf_token }}",
    },
    success: function(data){
      var answer = data.answer;
      $("#notification_badge").html(answer);
    }
  });

如何将这些组合到同一个请求中?我尝试将render 的结果添加到第二个视图中的数据中,但是 json.dumps 说它是不可序列化的。

【问题讨论】:

标签: python json ajax django django-views


【解决方案1】:

您无法序列化 Django 的 render 的输出,因为它是 returns an HttpResponse object,而不是字符串(这是您希望能够对其进行序列化的内容)。

一个好的解决方案是使用 render_to_string 将您的 html 返回到前端:

...
data = {
    "answer": 42,
    "html": render_to_string("my_app/my_template.html", context)
}
...

【讨论】:

  • 谢谢!我只需要将请求添加到 render_to_string 就可以了。
猜你喜欢
  • 1970-01-01
  • 2018-11-10
  • 2011-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-03
  • 2014-05-28
  • 2016-06-23
相关资源
最近更新 更多