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

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

问题描述

我是Django的新手,对Ajax来说很新。我正在开展一个需要整合两个项目的项目。我相信我了解他们背后的原则,但并没有找到对两者的良好解释。



有人可以快速说明代码库必须如何变化,两者集成在一起?



例如,我仍然可以使用Ajax的 HttpResponse ,还是使用Ajax来改变我的回应?如果是这样,你能否提供一个例子,说明如何响应请求必须改变?如果它有任何差异,我返回的数据是JSON。

解决方案

即使这不完全是在这个精神,我喜欢这个问题,因为我有同样的麻烦,当我开始,我会给你一个快速指南。显然,你不明白他们背后的原则(不要把它当成一个罪行,但如果你没有这样做)。



Django是服务器端。这意味着,说客户端去url,你有一个内部视图中的函数,呈现他看到的内容,并在html中返回一个响应。我们来分析一下例子:



views.py

  def (请求):
返回HttpResponse('Hello World!')

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

index.html:

 < h1>你好{{variable}},欢迎来到我的真棒网站< / 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 并将所有变量替换为所有(您现在可能知道所有这些变量)。



现在我们来谈谈AJAX。 AJAX调用是执行异步请求的客户端代码。这听起来很复杂,但它只是意味着它在后台执行一个请求,然后处理响应。所以当你对一些URL进行AJAX调用时,你会得到与用户去那个地方一样的数据。



例如,对 127.0.0.1:8000/hello 的ajax调用将返回与如果你访问它只有这一次,你才能在一个js函数内,你可以处理它,但是你想要的。我们来看一个简单的用例:

  $。ajax({
url: '127.0.0.1:8000/hello',
type:'get',//这是默认的,但实际上并不需要总是提到它
success:function(data){
alert(data);
},
失败:function(data){
alert('Got an error dude');
}
}) ;

一般过程是这样的:


  1. 呼叫转到url 127.0.0.1:8000/hello ,就像您打开一个新的标签一样,自己做了。

  2. 如果成功(状态码200),请执行成功功能,这将提醒收到的数据。

  3. 如果失败,请执行其他功能。 >

现在这里会发生什么?你会得到一个hello world的警报。如果你做一个ajax电话到家里会怎么样?同样的事情,你会得到一个警报,说明< h1> Hello world,欢迎来到我的真棒网站< / h1>



换句话说 - 没有关于AJAX调用的新功能。它们只是让用户在不离开页面的情况下获取数据和信息的一种方式,它可以让您的网站平滑而非常整齐的设计。您应该注意一些指导原则:


  1. 学习jQuery 。我不能强调这点。你必须明白一点,知道如何处理你收到的数据。您还需要了解一些基本的JavaScript语法(不远处的python,你会习惯它)。我强烈建议您 Envato的jQuery视频教程,他们是伟大的,将会把你放在正确的路径上。

  2. 何时使用JSON?。您将看到很多示例,其中由Django视图发送的数据是JSON。我没有详细说明,因为 在中不重要(有很多解释很多),而且更重要的是当。而答案是 - JSON数据是序列化数据。也就是说,你可以操纵的数据。像我所说的一样,AJAX调用将像用户自己一样获取响应。现在说你不想混淆所有的html,而是想发送数据(也许是一个对象的列表)。 JSON对它很有好处,因为它将它作为一个对象发送(JSON数据看起来像一个python字典),然后你可以迭代它,或者做一些其他的事情,不需要筛选无用的html。

  3. 最后添加。当你建立一个网络应用程序,并希望实现AJAX - 自己一个忙。首先,构建完全没有任何AJAX的整个应用程序。看到一切都正常。然后,只有这样,开始编写AJAX调用。这是一个很好的过程,可以帮助您学习很多。

  4. 使用chrome的开发人员工具。由于AJAX调用是在后台完成的,因此有时很难调试它们。您应该使用chrome开发工具(或类似的工具,如firebug)和 console.log 来进行调试。我不会详细解释,只是谷歌,并找出它。这对你来说非常有帮助。

  5. CSRF意识。最后,请记住,Django中的帖子请求需要 csrf_token 。使用AJAX调用,很多时候您想要发送数据而不刷新页面。你可能会遇到一些麻烦,最后记住这一点 - 等等,你忘了发送 csrf_token 。这是AJAX-Django集成中的一个已知的初学者路障,但是在你学习如何使其发挥好之后,这很容易,因为派别。




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?

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.

解决方案

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 is server-side. It means, say a client goes to 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'),

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).

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.

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 js 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');
    }
}); 

The general process is this:

  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 recieved.
  3. If fails, do a different function.

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>.

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. 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天全站免登陆