如何使用Django模板标签和过滤器与jQuery? [英] How to use Django template tags and filters with jQuery?

查看:213
本文介绍了如何使用Django模板标签和过滤器与jQuery?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一般的问题是这样的:我有一个包含内容的页面,用户可以对它进行评论。插入评论应该不会重新加载页面。

The problem in general is this: I have a page with content and user can comment it. Inserting comment should happen without reloading the page.

注释表单在将注释保存到数据库的视图中处理。保存评论后,我将新的评论序列化到json并返回页面。

Commenting form gets handled in a view which saves the comment to database. After saving the comment I serialize the new comment to json and return to the page.

data = serializers.serialize('json', [comment])
return HttpResponse(data, mimetype='application/javascript')

这个工作相当不错,评论被添加到div的顶部,但是如何将格式化标签应用于jQuery?评论是假设显示为

This works quite well, comment gets prepended to the top of a div, but how do I apply formatting tags to jQuery? Comment is suppose to be displayed as

<div class="comment">{{comment}}<br>{{ comment.created | timesince }}</div>

可以将模板标签应用于jQuery代码吗?当然有一个问题,其他评论不会更新,所以时代显示错误..要纠正这一点,我将不得不更新整个评论列表,并循环所有评论再次到页面,但同样的问题仍然是..

Is it possible to apply template tags to jQuery-code? Of course there's a problem that the other comments do not update, so the timesince is displayed wrong.. To correct this, I'd have to update whole comment list and loop all comments again to the page but the same problem still remains of course..

是否可以通过某种方式更新整个注释列表,将所有注释作为字典返回,并使jQuery加载模板以显示所有注释。

Is it possible to update whole listing of comments by somehow returning all comments as a dictionary and make jQuery load a template to display all comments..

或任何其他想法如何解决这个问题?

Or any other idea how to solve this problem?

推荐答案

而不是返回JSON ,通过渲染包含要更新的页面部分的模板来返回HTML。客户端jQuery代码可以插入新的HTML或根据需要替换现有的HTML。

Instead of returning JSON, return HTML by rendering a template that contains the portion of the page you want to update. The client-side jQuery code can then insert the new HTML or replace existing HTML as needed.

这篇关于如何使用Django模板标签和过滤器与jQuery?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆