将Django中的字符串列表传递给Javascript [英] Pass a list of string from Django to Javascript

查看:568
本文介绍了将Django中的字符串列表传递给Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Django对象有一个属性City。我正在尝试获取城市列表并使用Jquery在模板中捕获它(在X轴上的图表中使用)。

我的问题是我无法摆脱列表的unicode和引用。

(我设法为一个单独的值做)。相反,我坚持这个:

[[[u'Paris'],[u'Lyon']]]

My Django objects have an attribute "City". I'm trying to get a list of cities and catch it in the template with Jquery (to use in a chart on the X axis).
My problem is that I can't get rid of the unicode and quote for a list.
(I manage to do it for one single value). Instead I'm stucked with this:
["[[u'Paris'], [u'Lyon']]"]

I已经尝试了很多东西,包括JSON。没有成功。

I've tried tons of things, included JSON. No success.

我的观点:
(实际上,很多人中的一个尝试..)

My view: (actually, one of many try..)

def barchart1(request):
    city_array =[]
    for i in [1,MyObject.objects.count()]:
        objet = get_object_or_404(MyObject, pk=i)

        cities = [objet.city.city_name]
        city_array.append(cities)

return render (request, 'plot3/plot_page.html', {"city_array" : city_array}) 

我的JS:

<script type="text/javascript">
    var cities = ["{{ city_array }}"];
</script>

以下是JS如何阅读视图发送的上下文

[[[u'Paris'],[u'Lyon']]]

Here is how JS read the context sent by the view
["[[u'Paris'], [u'Lyon']]"]

这是我想要的

['巴黎','里昂']

Here is what I would like to get
['Paris', 'Lyon']

它必须简单但我无法弄清楚该怎么做它。
其他帖子不处理字符串列表。

It MUST be something simple but I just couldn't figure out how to do it. Others posts don't deal with a list of string.

我该怎么办?

推荐答案

当您在模板中执行 {{city_array}} 时,您的列表将转换为字符串。这是通过在列表上调用 repr()来完成的,该列表以递归方式对其内容调用 repr()。因为你的字符串是unicode,你会看到那些unicode文字, u'Paris'

When you do {{ city_array }} in your template, your list is converted to a string. This is done by calling repr() on the list, which recursively calls repr() on its contents. Because your strings are unicode, you see those unicode literals, u'Paris'.

正确的方式这样做是为了将你的数据编码为json,例如在你的视图中:

The "correct" way to do this is to encode your data to json, for example in your view:

import json
# ...
json_cities = json.dumps(city_array)
# ...
return render (request, 'plot3/plot_page.html', {"city_array" : json_cities})

然后执行

var cities = {{ city_array|safe }};

请注意:不要将此用于用户控制器数据!请参阅 OSWASP的XSS备忘单和有关 Django ticket 17419 的讨论,以获取更多信息。为了防止XSS,您可以使用 SafeJSONEncoder之类的内容。 django-cms项目

Please note: don't use this for user-controller data! See the XSS Cheat Sheet by OSWASP and the discussion on Django ticket 17419 for further information. To prevent XSS, you could use something like the SafeJSONEncoder from the django-cms project.

这篇关于将Django中的字符串列表传递给Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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