【问题标题】:How to handle python unicode string in javascript?如何在javascript中处理python unicode字符串?
【发布时间】:2014-03-16 22:28:28
【问题描述】:

字符串值是 unicode 字符串的字典,例如 {'name': u'nav', 'school': u'mps'}

javascript 中,我正在尝试访问该字典,例如

<script>
var poi = {{ dict }}  ........... //Line #1
alert( poi.name )
</script>

在渲染 html 页面时,第 1 行被渲染为(错误):

{'lastname': u'yadav', 'age': 23, 'id': 2, 'firstname': u'sahenky'}

一种 python 解决方案是将 unicode 字符串编码为其他格式,如 ascii 或 utf-8(首选)

str = u'nav'
str.encode('utf-8, 'ignore')
>>str
nav

有什么优雅的方法可以在 python 或 javascript 中编码 unicode 字符串?

【问题讨论】:

    标签: javascript unicode django-templates


    【解决方案1】:

    不是将实际的 dict 传递给模板,而是首先对其进行 JSON 编码:

    import json
    json.dumps(dict)
    

    【讨论】:

      猜你喜欢
      • 2019-09-04
      • 1970-01-01
      • 2010-12-11
      • 2018-09-21
      • 1970-01-01
      • 1970-01-01
      • 2014-12-05
      • 2011-08-11
      • 1970-01-01
      相关资源
      最近更新 更多