简体   繁体   English

使用 Django 将 JSON 数据传递到前端

[英]Passing JSON data to the front end using Django

Is there a way to pass JSON objects to the front end of a web template if using the Django framework or Python in general? Is there a way to pass JSON objects to the front end of a web template if using the Django framework or Python in general?

For example, if I want to send an object that has two arrays as properties (let's say xvalues and yvalues ), how would I be able to use JavaScript or jQuery to do an Ajax call to obtain the object that has the properties? For example, if I want to send an object that has two arrays as properties (let's say xvalues and yvalues ), how would I be able to use JavaScript or jQuery to do an Ajax call to obtain the object that has the properties?

Sure, just setup a view that returns JSON and make a request to it.当然,只需设置一个返回 JSON 的视图并向其发出请求。 Here's a simple example:这是一个简单的例子:

import json      
from django.http import HttpResponse
from django.template import Template, Context

def ajax(request):
    """returns json response"""
    return HttpResponse(json.dumps({'foo': 'bar'}), mimetype='application/json')

def index(request):
    """simple index page which uses jquery to make a single get request to /ajax, alerting the value of foo"""
    t = Template("""
    <!doctype html>
      <head>
       <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
       <script type="text/javascript">
         $.get('/ajax/', function(data) {
           alert(data['foo']);
         });
       </script>
     </head>
    </html>""")
    return HttpResponse(t.render(Context()))

# urlconf
urlpatterns = patterns('',
    (r'^$', index),
    (r'^ajax/', ajax),
)

If I understand you correctly, you want to render some JSON in your HTML output.如果我理解正确,您想在 HTML output 中渲染一些 JSON。

To do this, pass the json-encoded object from the view to the template:为此,请将 json 编码的 object 从视图传递到模板:

views.py : views.py

import json

def myview(request):
    obj = {"a": 1, "b": 2}
    return render_to_response("template.html", {"obj_as_json": json.dumps(obj)})

template.html : template.html

<html>
    <head>
    <script type="text/javascript">
    var obj = {{ obj_as_json|safe }};
    </script>
    </head>
    ...
</html>

Will render as:将呈现为:

...
<script type="text/javascript">
var obj = {"a": 1, "b": 2};
...

Note that json.dumps only works with dictionaries containing simple data types.请注意, json.dumps仅适用于包含简单数据类型的字典。 Django has support for serializing model objects to json, using: Django 支持将 model 对象序列化为 json,使用:

from django.core import serializers
obj_as_json = serializers.serialize("json", my_model_object)

Update: note that you need to use "safe" to get this:更新:请注意,您需要使用“安全”来获取此信息:

  var obj = {"items": [{"human": "Genesis", "usfm": "GEN"},],}

instead of this:而不是这个:

  var obj = {&quot;items&quot;: [{&quot;human&quot;: &quot;Genesis&quot;, &quot;usfm&quot;: &quot;GEN&quot;},],}

Complementing zeekay answer, if you want to send only an object you could do a json dump, for example:作为 zeekay 答案的补充,如果您只想发送 object 您可以进行 json 转储,例如:

import json

def my_ajax_view(request):
    if not request.is_ajax():
        raise Http404

    data_dict = getmydata() #lets supose is a dict
    return HttpResponse(json.dumps(data_dict))

That way you will receive that data via your ajax success and do whatever you want with it.这样,您将通过 ajax 成功接收该数据,并使用它做任何您想做的事情。

You can send over lists too, when you receive your response sometimes you will need to do a JSON.parse on data (sometimes cause when you send a dictionary I think is not necessary)您也可以发送列表,当您收到回复时,有时您需要对数据执行 JSON.parse (有时在您发送字典时我认为没有必要)

Unfortunately, the present answers are a bit outdated, here's how to do this with more recent versions of Django (including Django > 2.0 ):不幸的是,目前的答案有点过时了,这里是如何使用更新版本的 Django (包括Django > 2.0 )做到这一点:

Use JsonResponse , a subclass of HttpResponse , for this:为此,请使用JsonResponseHttpResponse的子类):

# views.py
from django.http import JsonResponse

def get_coords(request):
    """returns json response"""
    json_data = {'xval': 10, 'yval': 10}
    return JsonResponse(json_data)

It assumes a dict as parameter, but you can pass any JSON-serializable, in principle.它假定dict作为参数,但原则上您可以传递任何 JSON 可序列化。 I would discourage you from doing so, but if you pass an object that is not a dict you need to set the parameter safe=False .我不鼓励你这样做,但如果你传递一个不是dict的 object ,你需要设置参数safe=False

The ajax-request might look something like: ajax 请求可能类似于:

# index.html
...
<head>
...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
    $.get("{% url 'ajax_get_coords' %}", function(data) {
        var xval = data.xval;
        var yval = data.yval;
        ...
    });
</script>
...

With the corresponding urlconfig:使用相应的 urlconfig:

# urls.py

urlpatterns = [
   path('ajax_coords/', views.get_coords, name='ajax_get_coords'),
   ...

As of Django 2.1 there is another way to pass JSON objects to the front-end by including them in the template and using the json_script template filter.从 Django 2.1 开始,还有另一种方法可以通过将 JSON 对象包含在模板中并使用json_script模板过滤器将它们传递到前端。 This will create a script tag in the HTML and include the JSON within that.这将在 HTML 中创建一个脚本标签,并在其中包含 JSON。 This is useful for including the JSON in the download of the HTML page.这对于在 HTML 页面的下载中包含 JSON 非常有用。

Your template would use the tag like so:您的模板将像这样使用标签:

{{ your_json_object | json_script: "element_id" }}

Where your_json_object is a template variable containing an object that can be parsed into JSON.其中your_json_object是一个模板变量,其中包含可以解析为 JSON 的 object。

The HTML output would be: HTML output 将是:

<script id="element_id">{['json', 'object']}</script> 

And you can access it in a later Javascript file with:您可以在以后的 Javascript 文件中访问它:

let my_json = JSON.parse(document.getElementByID('element_id').textContent)

Checkout the documentation .查看文档

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

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