将字符串列表从 Django 传递给 Javascript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21150133/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pass a list of string from Django to Javascript
提问by xavier carbonel
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']]"]
我的 Django 对象有一个属性“城市”。我正在尝试获取城市列表并使用 Jquery 在模板中捕获它(在 X 轴上的图表中使用)。
我的问题是我无法摆脱列表的 unicode 和引用。
(我设法为一个单一的价值做到这一点)。相反,我坚持这个:
["[[u'Paris'], [u'Lyon']]"]
I've tried tons of things, included JSON. No success.
我已经尝试了很多东西,包括 JSON。没有成功。
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})
My JS:
我的JS:
<script type="text/javascript">
var cities = ["{{ city_array }}"];
</script>
Here is how JS read the context sent by the view
["[[u'Paris'], [u'Lyon']]"]
下面是JS如何读取视图发送的上下文
["[[u'Paris'], [u'Lyon']]"]
Here is what I would like to get
['Paris', 'Lyon']
这是我想要的
['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.
这一定是一些简单的事情,但我就是不知道该怎么做。其他帖子不处理字符串列表。
Any idea of what should I do?
知道我该怎么做吗?
回答by sk1p
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'
.
当您{{ city_array }}
在模板中执行此操作时,您的列表将转换为字符串。这是通过调用repr()
列表来完成的,该列表递归地调用repr()
其内容。因为您的字符串是 unicode,所以您会看到那些 unicode 文字u'Paris'
.
The "correct" way to do this is to encode your data to json, for example in your view:
执行此操作的“正确”方法是将您的数据编码为 json,例如在您的视图中:
import json
# ...
json_cities = json.dumps(city_array)
# ...
return render (request, 'plot3/plot_page.html', {"city_array" : json_cities})
and then do
然后做
var cities = {{ city_array|safe }};
in the template.
在模板中。
Please note: don't use this for user-controller data!See the XSS Cheat Sheet by OSWASPand the discussion on Django ticket 17419for further information. To prevent XSS, you could use something like the SafeJSONEncoder from the django-cms project.
请注意:不要将其用于用户控制器数据!有关更多信息,请参阅OSWASP的XSS Cheat Sheet和关于Django 票证 17419的讨论。为了防止 XSS,您可以使用django-cms 项目中的SafeJSONEncoder 之类的东西。