如何将 Ajax 与 Django 应用程序集成? [英] How do I integrate Ajax with Django applications?

查看:43
本文介绍了如何将 Ajax 与 Django 应用程序集成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Django 的新手,也是 Ajax 的新手.我正在做一个项目,我需要将两者结合起来.我相信我理解它们背后的原理,但还没有找到对两者的很好的解释.

I am new to Django and pretty new to Ajax. I am working on a project where I need to integrate the two. I believe that I understand the principles behind them both, but have not found a good explanation of the two together.

有人可以快速解释一下代码库必须如何随着它们两个集成在一起而发生变化吗?

Could someone give me a quick explanation of how the codebase must change with the two of them integrating together?

例如,我是否仍然可以将 HttpResponse 与 Ajax 一起使用,或者我的响应是否必须随着 Ajax 的使用而改变?如果是这样,您能否举例说明对请求的响应必须如何改变?如果它有任何区别,我返回的数据是 JSON.

For example, can I still use the HttpResponse with Ajax, or do my responses have to change with the use of Ajax? If so, could you please provide an example of how the responses to the requests must change? If it makes any difference, the data I am returning is JSON.

推荐答案

尽管这并不完全符合 SO 精神,但我喜欢这个问题,因为我刚开始时也遇到了同样的问题,所以我会给你快速指南.显然你不理解它们背后的原则(不要认为这是冒犯,但如果你理解了,你就不会问了).

Even though this isn't entirely in the SO spirit, I love this question, because I had the same trouble when I started, so I'll give you a quick guide. Obviously you don't understand the principles behind them (don't take it as an offense, but if you did you wouldn't be asking).

Django 是服务器端.这意味着,假设客户端访问一个 URL,您在 views 中有一个函数,该函数呈现他所看到的内容并以 HTML 格式返回响应.让我们把它分成几个例子:

Django is server-side. It means, say a client goes to a URL, you have a function inside views that renders what he sees and returns a response in HTML. Let's break it up into examples:

views.py:

def hello(request):
    return HttpResponse('Hello World!')

def home(request):
    return render_to_response('index.html', {'variable': 'world'})

index.html:

<h1>Hello {{ variable }}, welcome to my awesome site</h1>

urls.py:

url(r'^hello/', 'myapp.views.hello'),
url(r'^home/', 'myapp.views.home'),

这是最简单的用法示例.转到 127.0.0.1:8000/hello 意味着对 hello() 函数的请求,转到 127.0.0.1:8000/home 将返回 index.html 并按照要求替换所有变量(您现在可能已经知道了所有这些).

That's an example of the simplest of usages. Going to 127.0.0.1:8000/hello means a request to the hello() function, going to 127.0.0.1:8000/home will return the index.html and replace all the variables as asked (you probably know all this by now).

现在让我们谈谈 AJAX.AJAX 调用是执行异步请求的客户端代码.这听起来很复杂,但这只是意味着它在后台为您发出请求,然后处理响应.因此,当您对某个 URL 执行 AJAX 调用时,您将获得与用户访问该地点时获得的数据相同的数据.

Now let's talk about AJAX. AJAX calls are client-side code that does asynchronous requests. That sounds complicated, but it simply means it does a request for you in the background and then handles the response. So when you do an AJAX call for some URL, you get the same data you would get as a user going to that place.

例如,对 127.0.0.1:8000/hello 的 AJAX 调用将返回与您访问它时相同的内容.只是这一次,您将它放在一个 JavaScript 函数中,您可以随心所欲地处理它.让我们看一个简单的用例:

For example, an AJAX call to 127.0.0.1:8000/hello will return the same thing it would as if you visited it. Only this time, you have it inside a JavaScript function and you can deal with it however you'd like. Let's look at a simple use case:

$.ajax({
    url: '127.0.0.1:8000/hello',
    type: 'get', // This is the default though, you don't actually need to always mention it
    success: function(data) {
        alert(data);
    },
    failure: function(data) { 
        alert('Got an error dude');
    }
}); 

大致流程是这样的:

  1. 调用会转到 URL 127.0.0.1:8000/hello,就像您自己打开了一个新标签页一样.
  2. 如果成功(状态码200),执行成功的函数,它会提醒接收到的数据.
  3. 如果失败,请执行不同的功能.
  1. The call goes to the URL 127.0.0.1:8000/hello as if you opened a new tab and did it yourself.
  2. If it succeeds (status code 200), do the function for success, which will alert the data received.
  3. If fails, do a different function.

现在这里会发生什么?您会收到带有hello world"的警报.如果您使用 AJAX 调用 home 会发生什么?同样的事情,你会收到一条警告,说明

Hello world,欢迎来到我很棒的网站

.

Now what would happen here? You would get an alert with 'hello world' in it. What happens if you do an AJAX call to home? Same thing, you'll get an alert stating <h1>Hello world, welcome to my awesome site</h1>.

换句话说 - AJAX 调用并没有什么新鲜事.它们只是让用户无需离开页面即可获取数据和信息的一种方式,它使您的网站设计流畅且非常整洁.您应该注意的一些准则:

In other words - there's nothing new about AJAX calls. They are just a way for you to let the user get data and information without leaving the page, and it makes for a smooth and very neat design of your website. A few guidelines you should take note of:

  1. 学习 jQuery.我怎么强调这一点都不为过.您必须稍微了解它才能知道如何处理您收到的数据.您还需要了解一些基本的 JavaScript 语法(距离 Python 不远,您会习惯的).我强烈推荐 Envato 的 jQuery 视频教程,它们很棒而且会让你走上正确的道路.
  2. 何时使用 JSON?.您将看到很多示例,其中 Django 视图发送的数据采用 JSON 格式.我没有详细说明,因为如何去做并不重要(有很多解释),重要的是什么时候.答案是 - JSON 数据是序列化数据.也就是说,您可以操作的数据.就像我提到的,AJAX 调用将获取响应,就像用户自己做的一样.现在说你不想弄乱所有的 html,而是想发送数据(也许是一个对象列表).JSON 对此很有用,因为它将它作为对象发送(JSON 数据看起来像一个 Python 字典),然后您可以对其进行迭代或执行其他操作,从而无需筛选无用的 html.
  3. 最后添加.当您构建 Web 应用程序并想要实现 AJAX 时 - 帮自己一个忙.首先,构建完全没有任何 AJAX 的整个应用程序.看到一切正常.然后,只有在那时,才开始编写 AJAX 调用.这是一个很好的过程,也可以帮助您学到很多东西.
  4. 使用 chrome 的开发者工具.由于 AJAX 调用是在后台完成的,因此有时很难调试它们.您应该使用 chrome 开发人员工具(或类似的工具,例如 firebug)和 console.log 来调试.我不会详细解释,只是谷歌搜索并了解它.这对您很有帮助.
  5. CSRF 意识.最后,记住 Django 中的 post 请求需要 csrf_token.对于 AJAX 调用,很多时候您希望在不刷新页面的情况下发送数据.在您最终记住之前,您可能会遇到一些麻烦 - 等等,您忘记发送 csrf_token.这是 AJAX-Django 集成中一个众所周知的初学者障碍,但是在您学会如何让它玩得更好之后,它就像馅饼一样简单.
  1. Learn jQuery. I cannot stress this enough. You're gonna have to understand it a little to know how to handle the data you receive. You'll also need to understand some basic JavaScript syntax (not far from python, you'll get used to it). I strongly recommend Envato's video tutorials for jQuery, they are great and will put you on the right path.
  2. When to use JSON?. You're going to see a lot of examples where the data sent by the Django views is in JSON. I didn't go into detail on that, because it isn't important how to do it (there are plenty of explanations abound) and a lot more important when. And the answer to that is - JSON data is serialized data. That is, data you can manipulate. Like I mentioned, an AJAX call will fetch the response as if the user did it himself. Now say you don't want to mess with all the html, and instead want to send data (a list of objects perhaps). JSON is good for this, because it sends it as an object (JSON data looks like a python dictionary), and then you can iterate over it or do something else that removes the need to sift through useless html.
  3. Add it last. When you build a web app and want to implement AJAX - do yourself a favor. First, build the entire app completely devoid of any AJAX. See that everything is working. Then, and only then, start writing the AJAX calls. That's a good process that helps you learn a lot as well.
  4. Use chrome's developer tools. Since AJAX calls are done in the background it's sometimes very hard to debug them. You should use the chrome developer tools (or similar tools such as firebug) and console.log things to debug. I won't explain in detail, just google around and find out about it. It would be very helpful to you.
  5. CSRF awareness. Finally, remember that post requests in Django require the csrf_token. With AJAX calls, a lot of times you'd like to send data without refreshing the page. You'll probably face some trouble before you'd finally remember that - wait, you forgot to send the csrf_token. This is a known beginner roadblock in AJAX-Django integration, but after you learn how to make it play nice, it's easy as pie.

这就是我想到的一切.这是一个庞大的主题,但是是的,可能没有足够的例子.只要按照自己的方式努力,慢慢地,你最终会得到它.

That's everything that comes to my head. It's a vast subject, but yeah, there's probably not enough examples out there. Just work your way there, slowly, you'll get it eventually.

这篇关于如何将 Ajax 与 Django 应用程序集成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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