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

4

2 回答 2

2

看起来它在输出时得到了 HTML 转义。如果你这样做怎么办?:

var results = {{ myposts|safe }};

(谨慎使用——您可能希望根据数据的来源执行一些转义。)

于 2012-08-23T11:07:54.410 回答
1

在模板中试试这个:

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

编辑:

在视图中:

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))
于 2012-08-23T10:40:19.163 回答