用django模板语言实现javascript

时间:2012-12-12 08:46:09

标签: javascript python django json django-templates

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

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

1 个答案:

答案 0 :(得分: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);
});