从JavaScript传递信息Django应用程序和背部 [英] Pass information from javascript to django app and back

查看:231
本文介绍了从JavaScript传递信息Django应用程序和背部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我想基本上建立在用户选择的ID的网页,该网页然后发送ID信息,蟒蛇,蟒蛇的地方使用该ID查询数据库,然后返回结果网页的显示。

So I'm trying to basically set up a webpage where a user chooses an id, the webpage then sends the id information to python, where python uses the id to query a database, and then returns the result to the webpage for display.

我不太清楚如何做到这一点。我知道如何使用Ajax调用来调用由蟒蛇产生的数据,但我不确定如何进行通信的初始ID信息的Django应用程序。是否可以说,查询网址像./app/id(IE / APP / 8),然后使用URL信息给蟒蛇的信息?我怎么会去有关编辑urls.py和views.py这样做呢?

I'm not quite sure how to do this. I know how to use an ajax call to call the data generated by python, but I'm unsure of how to communicate the initial id information to the django app. Is it possible to say, query a url like ./app/id (IE /app/8), and then use the url information to give python the info? How would I go about editing urls.py and views.py to do that?

谢谢

推荐答案

您在谈论AJAX。 AJAX总是需要3个(在技术上,只有两个:JavaScript并身兼二职)

You're talking about AJAX. AJAX always requires 3 pieces (technically, just two: Javascript does double-duty).

  1. 在客户端(使用Javascript在这种情况下),使请求
  2. 服务器(在这种情况下的Django视图)处理请求,并返回响应
  3. 在客户端(再次,JavaScript)的接收响应,并做了一些与它

您还没有指定一个preferred框架,但你会疯狂做AJAX没有某种形式的JavaScript框架,所以我会挑jQuery的为您服务。在code能pretty的很容易地适应任何JavaScript框架:

You haven't specified a preferred framework, but you'd be insane to do AJAX without a Javascript framework of some sort, so I'm going to pick jQuery for you. The code can pretty easily be adapted to any Javascript framework:

$.getJSON('/url/to/ajax/view/', {foo: 'bar'}, function(data, jqXHR){
    // do something with response
});

我用 $。的getJSON ,这是发送一个GET请求来一个网址,并自动解析响应为JSON,把它变成一个jQuery方便的方法Javascript对象这里通过为数据。第一个参数是,第二个参数是包含应与请求一起被发送的数据的Javascript对象的请求将被发送到(多个上,在一个位)的URL(它可以省略,如果你不需要发送任何数据),第三个参数是一个回调函数来处理从上成功服务器的响应。因此code这个简单的位包括1和第3上面列出。

I'm using $.getJSON, which is a jQuery convenience method that sends a GET request to a URL and automatically parses the response as JSON, turning it into a Javascript object passed as data here. The first parameter is the URL the request will be sent to (more on that in a bit), the second parameter is a Javascript object containing data that should be sent along with the request (it can be omitted if you don't need to send any data), and the third parameter is a callback function to handle the response from the server on success. So this simple bit of code covers parts 1 and 3 listed above.

接下来的部分是你的处理器,这当然会在这种情况下是一个Django视图。该视图的唯一要求是,它必须返回一个JSON响应:

The next part is your handler, which will of course in this case be a Django view. The only requirement for the view is that it must return a JSON response:

from django.utils import simplejson

def my_ajax_view(request):
    # do something
    return HttpResponse(simplejson.dumps(some_data), mimetype='application/json')

请注意,这个观点并不需要比所要求的要求其他任何参数。这是一个有点哲学的选择。恕我直言,真正的REST方式,数据应与请求获得通过,在URL中没有,但其他人可能而且确实不同意。最终的选择权在你。

Note that this view doesn't take any arguments other than the required request. This is a bit of a philosophical choice. IMHO, in true REST fashion, data should be passed with the request, not in the URL, but others can and do disagree. The ultimate choice is up to you.

另外请注意,这里我使用Django的simplejson库,它是最适合普通Python数据结构(列表,http://stardict.sourceforge.net/Dictionaries.php下载等)。如果你想返回一个Django模型实例或一个QuerySet,你应该使用串行库,而不是。

Also, note that here I've used Django's simplejson library which is optimal for common Python data structures (lists, dicts, etc.). If you want to return a Django model instance or a queryset, you should use the serializers library instead.

from django.core import serializers
...
data = serializers.serialize('json', some_instance_or_queryset)
return HttpResponse(data, mimetype='application/json')

现在,您有一个观点,所有你需要做的就是其连接成Django的URL模式将让Django的知道如何路由请求。

Now that you have a view, all you need to do is wire it up into Django's urlpatterns so Django will know how to route the request.

urlpatterns += patterns('',
    (r'^/url/to/ajax/view/$', 'myapp.views.my_ajax_view'),
)

这是哪里的哲学差异进来如果您选择通过URL本身来传递数据,你需要捕捉到它的URL模式:

This is where that philosophical difference comes in. If you choose to pass data through the URL itself, you'll need to capture it in the urlpattern:

(r'^/url/to/ajax/view/(?P<some_data>[\w-]+)/$, 'myapp.views.my_ajax_view'),

然后,修改以便接受它作为参数:

Then, modify your view to accept it as an argument:

def my_ajax_view(request, some_data):

最后,修改JavaScript AJAX方法把它列入网址:

And finally, modify the Javascript AJAX method to include it in the URL:

$.getJSON('/url/to/ajax/view/'+some_data+'/', function(data, jqXHR){

如果你去请求传递数据的途径,那么你需要注意正确的retreive它的观点:

If you go the route of passing the data with the request, then you need to take care to retreive it properly in the view:

def my_ajax_view(request):
    some_data = request.GET.get('some_data')
    if some_data is None:
        return HttpResponseBadRequest()

这应该给你足够的承担几乎所有的AJAX功能与Django的。还有什么是怎么一回事视图检索数据(手动创建它,查询数据库等),以及如何你的Javascript回调方法处理JSON响应。上的一些技巧:

That should give you enough to take on just about any AJAX functionality with Django. Anything else is all about how your view retrieves the data (creates it manually, queries the database, etc.) and how your Javascript callback method handles the JSON response. A few tips on that:

  1. 数据对象的一般的是一个列表,即使只有一个项目被列入。如果你知道有只有一个项目,你可以使用数据[0] 。否则,使用一个for循环来访问每个项目:

  1. The data object will generally be a list, even if only one item is included. If you know there's only one item, you can just use data[0]. Otherwise, use a for loop to access each item:

form (var i=0; i<data.length; i++) {
    // do something with data[i]
}

  • 如果数据数据[I] 是一个对象(也就是字典,哈希,keyed-阵列等),您可以通过将按键的属性访问该键的值,例如:

  • If data or data[i] is an object (AKA dictionary, hash, keyed-array, etc.), you can access the values for the keys by treating the keys as attributes, i.e.:

    data[i].some_key
    

  • 在使用JSON反应和AJAX一般处理,通常最好在浏览器中直接先试用一下,因此您可以查看精确的响应和/或验证响应的结构。要查看JSON响应在浏览器中,你很可能需要一个exstention。 JSONView(同时适用于火狐和的 Chrome浏览器)使它能够理解JSON,并显示它像一个网页。如果请求是一个GET,你可以使用查询字符串,即 http://mydomain.com/url/to/ajax/view/?some_data=foo <数据传递到正常GET方式的URL / code>。如果它是一个POST,你需要某种形式的REST测试客户端。 RESTClient 是一个很好的插件用于Firefox。对于Chrome浏览器,你可以尝试邮差。这也是来学习的推特,脸谱等第三方的API。

  • When dealing with JSON responses and AJAX in general, it's usually best to try it directly in a browser first so you can view the exact response and/or verify the structure of the response. To view JSON responses in your browser, you'll most likely need an exstention. JSONView (available for both Firefox and Chrome) will enable it to understand JSON and display it like a webpage. If the request is a GET, you can pass data to the URL in normal GET fashion using a querystring, i.e. http://mydomain.com/url/to/ajax/view/?some_data=foo. If it's a POST, you'll need some sort of REST test client. RESTClient is a good addon for Firefox. For Chrome you can try Postman. These are also great for learning 3rd-party APIs from Twitter, Facebook, etc.

    这篇关于从JavaScript传递信息Django应用程序和背部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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