3

I have a small problem when my code is retrieved by javaScript from Python, i get unicode values to my script where my browser gives an error in the developer console.

The script inside my archive.html page -

<script>
    var results = {{myposts}};
    console.log(results);
</script>

My Python code -

def archive(request):
    test = ["a","b","c"]
    t = loader.get_template("archive.html")
    c = Context({'myposts' : test})
    return HttpResponse(t.render(c))

I tried c = Context({'myposts' : simplejson.dumps(test)}) , but it gave the problem. My browsers give me and arror Uncaught SyntaxError: Unexpected token & and my console shows my array with unicode values [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;]

How do i make it look like - ["a","b","c"]

What do i change in my Python code or JavaScript

Thanks for the help in advance

3
  • 3
    Your values are being HTML escaped; this is not a Unicode problem. :-) Commented Aug 23, 2012 at 10:41
  • 1
    You might get ASCII or ISO-8859-1 or UTF-8 but you will never get Unicode. Unicode ist just the idea, the realization in memory (or on disk) differs. Commented Aug 23, 2012 at 11:04
  • @Matthias thanks for the tip, i am still learning my way through web development Commented Aug 23, 2012 at 11:25

2 Answers 2

2

Looks like it's getting HTML-escaped on output. What if you do this?:

var results = {{ myposts|safe }};

(Use with caution -- you may want to perform some escaping depending where the data is coming from.)

Sign up to request clarification or add additional context in comments.

1 Comment

It works perfectly, without needing to any changes to my python code
1

Try this in the template:

<script>
    var results = {{ myposts|escapejs }};
    console.log(results);
</script>

EDIT:

And in the view:

from django.utils import simplejson

def archive(request):
    test = ["a","b","c"]
    t = loader.get_template("archive.html")
    c = Context(simplejson.dumps({'myposts' : test}))
    return HttpResponse(t.render(c))

2 Comments

I get "Uncaught SyntaxError: Unexpected token ILLEGAL" in my browser console and my var results looks like this "var results = [\u0022a\u0022, \u0022b\u0022, \u0022c\u0022];"
The edited version gave me null value to my variable "var results = ;" and my browser console throws an error. But when i just did this on my JavaScript jsfiddle.net/gfCWp/3 it worked perfectly (forgive me for my noob style coding )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.