将信息从javascript传递到django应用程序并返回 [英] Pass information from javascript to django app and back

查看:97
本文介绍了将信息从javascript传递到django应用程序并返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图基本上设置用户选择一个id的网页,然后网页将id信息发送给python,其中python使用id查询数据库,然后将结果返回给网页显示。



我不太清楚如何做到这一点。我知道如何使用ajax调用来调用python生成的数据,但我不知道如何将初始id信息传达给django应用程序。可以说,查询像./app/id(IE / app / 8)这样的URL,然后使用url信息给python的信息?我如何去编辑urls.py和views.py?



谢谢,

解决方案

你在说AJAX。 AJAX总是需要3件(技术上只有两个:Javascript做双重工作)。


  1. 客户端(在这种情况下为Javascript) / li>
  2. 服务器(在这种情况下为Django视图)处理请求并返回响应

  3. 客户端(再次,Javascript)收到响应并执行某些操作

你没有指定一个首选框架,但是如果没有一个Javascript框架,你会疯狂地做AJAX,所以我是要为你挑选jQuery代码可以很容易地适应任何Javascript框架:

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

我正在使用 $。getJSON 这是一个jQuery方便的方法,它将一个GET请求发送到一个URL,并自动解析为JSON的响应,将其转换为以 data 传递的Javascript对象。第一个参数是请求发送到的URL(更多的是在一点),第二个参数是一个Javascript对象,包含应该与请求一起发送的数据(如果不需要,可以省略发送任何数据),第三个参数是一个回调函数来处理来自服务器的响应成功。所以这个简单的代码覆盖上面列出的第1部分和第3部分。



下一部分是你的处理程序,当然这也是一个Django视图。该视图的唯一要求是它必须返回JSON响应:

  from django.utils import simplejson 

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

请注意,此视图不需要任何参数,而不是所需的请求。这是一个哲学的选择。 IMHO,以真正的REST方式,数据应该与请求一起传递,而不是在URL中,但是其他人可以而且不同意。最终的选择取决于你。



此外,请注意,在这里我已经使用了Django的simplejson库,这对于常见的Python数据结构(列表,例子等)来说是最佳选择。 )。如果要返回一个Django模型实例或一个查询集,应该使用序列化程序库。

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

现在你有一个视图,所有你需要做的是将其连接到Django的urlpatterns,所以Django将知道如何路由请求。 / p>

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

这是哲学上的差异进来。如果您选择通过URL本身传递数据,则需要在urlpattern中捕获数据:

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

然后,修改你的视图来接受它一个参数:

  def my_ajax_view(request,some_data):

最后,修改Javascript AJAX方法将其包含在URL中:

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

如果您通过请求传递数据的路线,则需要在视图中正确地检索数据:



$ $ $ $ $ $ $ $ $ $ $
some_data = request.GET.get('some_data')
如果some_data为None:
返回HttpResponseBadRequest( )

这应该足以让您充分利用Django的任何AJAX功能。其他任何事情都是关于您的视图如何检索数据(手动创建,查询数据库等)以及JavaScript回调方法如何处理JSON响应。一些提示:


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

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


  2. 如果数据 data [i] 是一个对象(AKA字典,散列,键控数组等)您可以通过将密钥视为属性来访问密钥的值,即:

      data [i] .some_key 


  3. 在处理JSON响应和AJAX时,通常最好直接在浏览器中尝试首先,您可以查看确切的响应和/或验证响应的结构。要在浏览器中查看JSON响应,您很可能需要一个撤销。 JSONView(可用于 Firefox Chrome )将使其能够理解JSON并将其显示为网页。如果请求是GET,则可以使用querystring将数据传递给URL,方法如下: http://mydomain.com/url/to/ajax/view/?some_data=foo 。如果是POST,您将需要某种REST测试客户端。 RESTClient 是Firefox的一个很好的插件。对于Chrome,您可以尝试邮递员。这些也非常适合从Twitter,Facebook等学习第三方API。



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.

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?

Thanks,

解决方案

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

  1. Client (Javascript in this case) makes request
  2. Server (Django view in this case) handles request and returns response
  3. Client (again, Javascript) receives response and does something with it

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

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.

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

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.

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

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'),
)

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

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

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

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

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

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

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