简体   繁体   English

将信息从 javascript 传递到 django 应用程序并返回

[英]Pass information from javascript to django app and back

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.所以我试图基本上建立一个用户选择一个id的网页,然后网页将id信息发送给python,python使用id查询数据库,然后将结果返回给网页进行显示。

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.我知道如何使用 ajax 调用来调用由 python 生成的数据,但我不确定如何将初始 id 信息传达给 django 应用程序。 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?是否可以说,查询一个像 ./app/id (IE /app/8) 这样的 url,然后使用 url 信息给 python 信息? How would I go about editing urls.py and views.py to do that?我将如何编辑 urls.py 和 views.py 来做到这一点?

Thanks,谢谢,

You're talking about AJAX.你在谈论 AJAX。 AJAX always requires 3 pieces (technically, just two: Javascript does double-duty). AJAX 总是需要 3 个部分(从技术上讲,只有两个:Javascript 执行双重任务)。

  1. Client (Javascript in this case) makes request客户端(本例中为 Javascript)发出请求
  2. Server (Django view in this case) handles request and returns response服务器(本例中为 Django 视图)处理请求并返回响应
  3. Client (again, Javascript) receives response and does something with it客户端(再次,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.您还没有指定首选框架,但是如果没有某种 Javascript 框架,您会疯狂地使用 AJAX,所以我将为您选择 jQuery。 The code can pretty easily be adapted to any Javascript framework:代码可以很容易地适应任何 Javascript 框架:

$.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.我正在使用$.getJSON ,这是一种 jQuery 便捷方法,可将 GET 请求发送到 URL 并自动将响应解析为 JSON,将其转换为在此处作为data传递的 Javascript 对象。 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.第一个参数是请求将被发送到的 URL(稍后会详细介绍),第二个参数是一个 Javascript 对象,其中包含应该与请求一起发送的数据(如果您不需要,可以省略它发送任何数据),第三个参数是一个回调函数,用于在成功时处理来自服务器的响应。 So this simple bit of code covers parts 1 and 3 listed above.所以这段简单的代码涵盖了上面列出的第 1 部分和第 3 部分。

The next part is your handler, which will of course in this case be a Django view.下一部分是您的处理程序,在本例中当然是 Django 视图。 The only requirement for the view is that it must return a JSON response:该视图的唯一要求是它必须返回一个 JSON 响应:

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 .请注意,除了所需的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.恕我直言,在真正的 REST 方式中,数据应该与请求一起传递,而不是在 URL 中,但其他人可以并且确实不同意。 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.).另外,请注意,这里我使用了 Django 的 simplejson 库,它最适合常见的 Python 数据结构(列表、字典等)。 If you want to return a Django model instance or a queryset, you should use the serializers library instead.如果要返回 Django 模型实例或查询集,则应改用序列化程序库。

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.现在您有了一个视图,您需要做的就是将它连接到 Django 的 urlpatterns 中,以便 Django 知道如何路由请求。

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:这就是哲学差异的来源。如果您选择通过 URL 本身传递数据,则需要在 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:最后,修改 Javascript AJAX 方法以将其包含在 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.这应该足以让您使用 Django 来处理几乎任何 AJAX 功能。 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.其他任何事情都是关于您的视图如何检索数据(手动创建数据、查询数据库等)以及您的 Javascript 回调方法如何处理 JSON 响应。 A few tips on that:一些提示:

  1. The data object will generally be a list, even if only one item is included. data对象通常是一个列表,即使只包含一个项目。 If you know there's only one item, you can just use data[0] .如果您知道只有一项,则可以使用data[0] Otherwise, use a for loop to access each item:否则,使用 for 循环访问每个项目:

     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, ie:如果datadata[i]是一个对象(AKA 字典、散列、键控数组等),您可以通过将键视为属性来访问键的值,即:

     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.通常在处理 JSON 响应和 AJAX 时,通常最好先在浏览器中直接尝试,以便您可以查看确切的响应和/或验证响应的结构。 To view JSON responses in your browser, you'll most likely need an exstention.要在浏览器中查看 JSON 响应,您很可能需要一个扩展。 JSONView (available for both Firefox and Chrome ) will enable it to understand JSON and display it like a webpage. JSONView(可用于FirefoxChrome )将使其能够理解 JSON 并将其显示为网页。 If the request is a GET, you can pass data to the URL in normal GET fashion using a querystring, ie http://mydomain.com/url/to/ajax/view/?some_data=foo .如果请求是 GET,您可以使用查询字符串以正常的 GET 方式将数据传递到 URL,即http://mydomain.com/url/to/ajax/view/?some_data=foo If it's a POST, you'll need some sort of REST test client.如果是 POST,则需要某种 REST 测试客户端。 RESTClient is a good addon for Firefox. RESTClient是一个很好的 Firefox 插件。 For Chrome you can try Postman .对于 Chrome,您可以尝试Postman These are also great for learning 3rd-party APIs from Twitter, Facebook, etc.这些也非常适合从 Twitter、Facebook 等学习 3rd 方 API。

Yes, it is possible.对的,这是可能的。 If you pass the id as a parameter to the view you will use inside your app, like: def example_view (request,id) and in urls.py, you can use something like this: url(r'^example_view/(?P<id>\\d+)/', 'App.views.example_view') .如果您将 id 作为参数传递给您将在应用程序中使用的视图,例如: def example_view (request,id)和在 urls.py 中,您可以使用以下内容: url(r'^example_view/(?P<id>\\d+)/', 'App.views.example_view')

The id in the url /example_view_template/8 will get access to the result using the id which is related to the number 8. Like the 8th record of a specific table in your database, for example. url /example_view_template/8的 id 将使用与数字 8 相关的 id 访问结果。例如,就像数据库中特定表的第 8 条记录。

About how to capture info from ajax request/urls, Usually you can do that as in a normal django requests, check url dispatcher docs and read about django views from official docs.关于如何从 ajax 请求/url 捕获信息,通常您可以像在普通 django 请求中那样执行此操作,检查url 调度程序文档并从官方文档中阅读有关 django 视图的信息。

About how to return response, just capture the parameters, process your request then give your response with appropriate mimitype.关于如何返回响应,只需捕获参数,处理您的请求,然后使用适当的 mimitype 给出您的响应。

Sometimes you have to serialize or convert your data to another format like json which can be processed more efficiently in a client-side/js有时您必须将数据序列化或转换为另一种格式,例如 json,这样可以在客户端/js 中更有效地处理

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM