你的字符串包含换行符,所以
var data = JSON.parse('{{ data|safe }}');
不会工作。尝试使用反引号(不知道如何在此处输入)而不是 '。
但是,如果你已经将数据dump到json中,则不需要在JS端解析,直接做
var data = {{ data|safe }};
更新:注意,上面的模板变量没有引号,上面会变成(查看源代码):
var data = [
{
"model": "accounts.profile",
"pk": 14,
"fields": {
"user": 14,
"email_confirmed": true,
"encrypted_private_key": "Z0FBQUFBQmJLQT09",
"public_key": "LS0tLSS0tLQo=",
"salt": "I8rzovcWsKm4G5Pj3E4DMw=="
}
}
];
注意,它周围仍然没有引号。这是有效的 Javascript,无需进一步操作(即解析)。
update2:要在 .js 文件中使用此数据,您需要像这样更改 .js 文件:
var some_unique_name = function (data) {
... original code goes here ...
};
在你的 html 中:
<script src="...your script"></script>
<script>
some_unique_name({{ data|safe }});
</script>
update3:以上将扩展为(使用浏览器的查看源功能检查):
<script src="...your script"></script>
<script>
some_unique_name([
{
"model": "accounts.profile",
"pk": 14,
"fields": {
"user": 14,
"email_confirmed": true,
"encrypted_private_key": "Z0FBQUFBQmJLQT09",
"public_key": "LS0tLSS0tLQo=",
"salt": "I8rzovcWsKm4G5Pj3E4DMw=="
}
}
]);
</script>
这是有效的javascript。但是,您不能在 html 事件处理程序中盲目地做同样的事情,因为
<button type="button" onclick="some_unique_name({{ data|safe }})" ...>
将扩展为
<button type="button" onclick="some_unique_name([
{
"model": "accounts.profile", // syntax error here..
"pk": 14,
"fields": {
"user": 14,
"email_confirmed": true,
"encrypted_private_key": "Z0FBQUFBQmJLQT09",
"public_key": "LS0tLSS0tLQo=",
"salt": "I8rzovcWsKm4G5Pj3E4DMw=="
}
}
])" ...>
浏览器会看到的
<button type="button" onclick="some_unique_name([{"
它不明白。
如果我们暂时忽略 Django,有两个明显的解决方法:
(1)把函数的参数放在一个变量中:
<script>
var my_variable = [
{
"model": "accounts.profile", // syntax error here..
"pk": 14,
"fields": {
"user": 14,
"email_confirmed": true,
"encrypted_private_key": "Z0FBQUFBQmJLQT09",
"public_key": "LS0tLSS0tLQo=",
"salt": "I8rzovcWsKm4G5Pj3E4DMw=="
}
}
];
</script>
<button type="button" onclick="some_unique_name(my_variable);">..</button>
(2) 或将调用包装在一个函数中:
<script>
var foo = function () {
some_unique_name([
{
"model": "accounts.profile", // syntax error here..
"pk": 14,
"fields": {
"user": 14,
"email_confirmed": true,
"encrypted_private_key": "Z0FBQUFBQmJLQT09",
"public_key": "LS0tLSS0tLQo=",
"salt": "I8rzovcWsKm4G5Pj3E4DMw=="
}
}
]);
};
</script>
<button type="button" onclick="foo();">..</button>
回到 Django,这变成了
(1)
<script>
var my_variable = {{ data|safe }};
</script>
<button type="button" onclick="some_unique_name(my_variable);">..</button>
和
(2)
<script>
var foo = function () {
some_unique_name({{ data|safe }});
};
</script>
<button type="button" onclick="foo();">..</button>