如何将utf8数据从Django传递到javascrip

2024-06-28 10:57:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Django中有以下key-value对象:

data = {
    "id": 1,
    "question_text": "אנא בחר אחת מהתשובות הבאות",
    "answers": [
     {
        "label" : "תשובה 1",
        "value" : 1,
        "count" : 30
     },
     {
        "label" : "תשובה 2",
        "value" : 2,
        "count" : 30
     },
     {
        "label" : "תשובה 3",
        "value" : 3,
        "count" : 30
     },
}

请注意,有些数据是希伯来语的,因此当我将其保存到数据库中时,我使用:

^{pr2}$

当我试图将这个对象发送到视图时,为了在Django模板和Javascript中使用它

我用了这句话:

return render(request, 'reports/report.html', {'data': data })

在我使用的观点中:

var question_data = {{ data }} #in order to get the data object that was sent to the view

但我得到这样一个元素:

{'bad': 45, 'good': 55, 'question_text': u'\u05e2\u05d3 \u05db\u05de\u05d4 \u05d0\u05ea\u05d4 \u05de\u05e8\u05d5\u05e6\u05d4 \u05d0\u05d5 \u05dc\u05d0 \u05de\u05e8\u05d5\u05e6\u05d4 \u05de\u05d1\u05d2\u05d3\u05d9 \u05e2\u05dc\u05d9\u05ea \u05d1\u05d0\u05d5\u05e4\u05df \u05db\u05dc\u05dc\u05d9?', 'id': u'8', 'answers': [{'value': 30, 'label': u'\u05de\u05d0\u05d5\u05d3 \u05de\u05e8\u05d5\u05e6\u05d4'}, {'value': 25, 'label': u'\u05d3\u05d9 \u05de\u05e8\u05d5\u05e6\u05d4'}, {'value': 20, 'label': u'\u05dc\u05d0 \u05db\u05dc \u05db\u05da \u05de\u05e8\u05d5\u05e6\u05d4'}, {'value': 25, 'label': u'\u05db\u05dc\u05dc \u05dc\u05d0 \u05de\u05e8\u05d5\u05e6\u05d4'}]}

控制台中的这个错误:

SyntaxError: Unexpected token '&'. Expected a property name

我还尝试使用:

var question_data = {{ data|safe }}

我得到了一个错误:

[Error] SyntaxError: Unexpected string literal '\u05e2\u05d3 ...

我使用的是django1.7和python2.7.6

请试着帮助我理解我做错了什么


Tags: datavaluecountlabelquestionu05dcu05d5u05d0
2条回答

对于show JSON fron Views Django,必须使用筛选器转义数据:

var categories = JSON.parse("{{ categories|escapejs }}");

查看

import json
# ....
return render(request, 'reports/report.html', {'data': json.dumps(data) })

模板

^{pr2}$

另外,python dict中可能有语法错误(缺少右括号)。在

编辑

return render(request, 'reports/report.html', {'data': data, 'data_json': json.dumps(data) })

相关问题 更多 >