Django的:如何在不U''阵列转移到JavaScript的? [英] Django: how to transfer array to javascript without u' '?

查看:132
本文介绍了Django的:如何在不U''阵列转移到JavaScript的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在访问量:

'some_array': ['text1','text2', 'text3']

当我尝试它在模板转移到js脚本:

When I try to transfer it in template to js script:

<script type="text/javascript">
    some_func({{ some_array }});
</script>

在源$ C ​​$ C,它看起来像:

In source code it looks like:

<script type="text/javascript">
    some_func([u'text1', u'text2', u'text3']);
</script>

因此​​,它是在JavaScript错误。

So it is an error in javascript.

如何删除preFIX U''从数组元素或如何解决这个问题?

How to remove prefix u'' from array's elements or how to get around this?

谢谢!

推荐答案

当你转移Python列表转换为字符串,要创建的Python的重新您的变量presentation( __再版__ )。你正试图在这里做的是创建同一数据的一个JavaScript重新presentation。

When you transfer a Python list into a string, you are creating the Python representation of your variable (__repr__). What you are trying to do here is create a JavaScript representation of the same data.

JSON是因为如此多的语言有很好的JSON解析器来传输数据的好办法。在JavaScript的情况下,由于JSON是本地实际JavaScript语法,所以你可以把JSON重新presentation直插入JavaScript源,这是更加真实的。

JSON is a great way to transfer data because so many languages have good JSON parsers. In the case of JavaScript this is even more true since JSON is actually native JavaScript syntax so you can put the JSON representation straight into the JavaScript source.

要生成JSON,您可以使用Python的内置JSON库(Python的2.6 +)。

To generate the JSON, you can use Python's built-in JSON library (Python 2.6+).

>>> import json
>>> json.dumps([u'text1', u'text2', u'text3'])
'["text1", "text2", "text3"]'

这将创建一个可以在你的模板中使用的字符串。

This creates a string that can be used in your template.

这篇关于Django的:如何在不U''阵列转移到JavaScript的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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