0
{% with JSONContent as object %}{% include "_comments.html" %}{% endwith %}

JSONContent 是我通过$.get()方法获得的 django 模型实例。“_comments.html”是一个未渲染的评论模板。我想渲染该模板,并通过 AJAX 将其发送到客户端(因此,revieved 数据是模板中渲染的 HTML)我该怎么做?

4

1 回答 1

1

听起来您正在从 ajax 请求到服务器获取模型实例,并且您想在“_comments.html”模板中使用该实例。那正确吗?如果是这样,您可以改为在服务器上呈现模板并在 ajax 请求中获取呈现的 HTML。

因此,假设您有一个fetch_new_comments处理 ajax 请求的视图。视图可能看起来像这样,而不是获取评论模型并将其转储到 JSON 并返回它:

def fetch_new_comments(request):
  comments = ... # get whatever data you're using
  return render_to_response("_comments.html", {"comments": comments})

因此,这意味着您的 ajax 请求将收到一大块 HTML(而不是 JSON 对象),并将其插入页面。如果你使用 jQuery,你可以这样做:

$.get("http://yoursite.com/fetch_new_comments/", function (resp) {
  $("#new_comments_container").html(resp);
});
于 2012-12-12T22:46:08.307 回答