Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
431 views
in Technique[技术] by (71.8m points)

jquery - Pass a list of string from Django to Javascript

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

My 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']]"]

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.

Any idea of what should I do?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...