使用 django 进行 Ajax 视图
我现在正在开发一个相当大的项目,其中每个视图都应该可以通过普通请求和 ajax 请求通过相同的 url 访问。我正在寻找有关如何创建一个小型框架来以非常通用的方式处理此问题的想法。根据视图是否通过 ajax 调用,它需要渲染不同的模板并返回 json 而不是 HttpResponse 对象。我想收集有关此主题的任何想法 - 主要目标应该是不要避免干燥原则并制作尽可能可重用的代码。我已经在考虑不同的选项,如通用视图、视图装饰器等,但我对任何事情都持开放态度。因此,请让我听听您的建议或向我指出您知道的任何现成的片段!
I'm working on a pretty big project right now where every view should be accessible via a normal request and an ajax request via the same url. I'm looking for ideas on how to create a small framework to handle this in a very generic way. Depending on if the view is called via ajax or not it needs to render a different template and return a json instead of a HttpResponse
object. I'd like to collect any ideas on this topic - the main goal should be not to avoid the dry principle and make code that is as reusable as possible. I was already considering different options as generic views, decorators on views etc, but I'm open to anything. So please let me hear your suggestions or point me towards any readymade snippets you know!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这篇文章似乎是一个关于如何使用的非常好的教程ajax 和常规请求。
request
对象有一个is_ajax()
方法,它将查找HTTP_X_REQUESTED_WITH: XMLHttpRequest
。这当然取决于发送请求的 JavaScript 是否正确设置了这些值。来自文章:
或者,您可以使用 django-piston 这是一个 RESTful 框架为了姜戈。我在我的项目中使用这个模块。您可以定义资源(有点像视图),并且根据传递给您的 url 的 mime 类型或格式,它将发出 html、xml 或 json。如果每个视图(或大多数)需要以不同的格式返回,这可能是最好的方法。
This article seems to be quite a good tutorial on how to work with both ajax and regular requests. The
request
object has a methodis_ajax()
which will look forHTTP_X_REQUESTED_WITH: XMLHttpRequest
. This will of course depend on these values being set correctly by the javascript sending the request.From the article:
Or, you could use django-piston which is a RESTful framework for Django. I use this module in my project. You can define resources (sort of like views), and depending on either the mime-type or format passed to your url, it will emit either html, xml, or json. This will probably be the best way to go if every single view (or a large majority) need to be returned in different formats.
我为此使用了装饰器。让视图返回上下文、模板和备用模板。
如果Ajax版本要返回数据,第三个返回值可以是要转成JSON的数据对象。
I have used a decorator for this. Have the view return the context, the template, and an alternate template.
If the Ajax version wants to return data, the third return value can be the data object to turn into JSON.