gpt4 book ai didi

javascript - 从 Django 获取一个列表到 Javascript 作为一个数组

转载 作者:行者123 更新时间:2023-11-30 06:21:08 25 4
gpt4 key购买 nike

我有一个由 Django 中的 views.py 生成的 python 列表,我想将它传递给 HTML 模板中的 javascript。我似乎无法将它作为一个数组放入 javscript 中...我需要评估列表/数组是否包含某些数字,但它是以字符串的形式出现的。

我将列表传递给我的 HTML 模板,如下所示:

def get_context_data(self, **kwargs):
context = super(dashboardView, self).get_context_data(**kwargs)
mylist = [10,22,33,45]
context['mylist'] = mylist
return context

当我使用时:

<h1 id = "list"> {{mylist}}</h1>

它在浏览器上显示为它显示为 [10,22,33,45]

然后在我的模板中使用 javascript 我有:

var mylist = document.getElementById("list").innerHTML;
for(i = 0; i < mylist.length; i++){
console.log(mylist[i])
};

这在控制台中返回:

'
[
1
0
,

2
2
........

我要:

10
22
33
45

我曾尝试在 python 中转换为 JSON,并在 javascript 中解析它,但似乎无法将此字符串转换为数组,或者不断出错。对这里的最佳方法有什么想法吗?

最佳答案

如果您绝对确定您的列表是安全的(我的意思是它永远不会包含用户输入的任何内容),那将非常简单。

在你看来:

context={"my_list": ["item1", "item2"]}

在你的模板中:

{{ my_list|safe }}

呈现为:

['item1', 'item2']

例如:

{{ my_list|safe }}.forEach(item => {
console.log(item)
})

令人印象深刻的是,如果您传递带撇号的字符串,Django 会自动更改引号类型,因此

context = {"my_list": ["item1", "it'em2"]}

呈现为(注意双引号):

['item1', "it'em2"]

所以

{{ my_list|safe }}.forEach

仍然有效(在 Django 3.2.6 上测试)。

即使这样也行得通:

context = {"my_list": ["item1", "it'em\"2"]}

呈现为:

['item1', 'it\'em"2']

所以

{{ my_list|safe }}.forEach

仍然有效。

但是,正如我在顶部所说,如果您的列表可能包含来自用户的输入,我仍然不会相信这种方法。

==

编辑:现在这是最高的答案,我想添加一种更安全的方法来使其更容易完全安全。这很有趣django-argonauts ,虽然我不是安全专家,所以无法确认该方法:

@register.filter(is_safe=True)
def jsonify(json_object):
"""
Output the json encoding of its argument.
This will escape all the HTML/XML special characters with their unicode
escapes, so it is safe to be output anywhere except for inside a tag
attribute.
If the output needs to be put in an attribute, entitize the output of this
filter.
"""

json_str = json.dumps(json_object)

# Escape all the XML/HTML special characters.
escapes = ["<", ">", "&"]
for c in escapes:
json_str = json_str.replace(c, r"\u%04x" % ord(c))

# now it's safe to use mark_safe
return mark_safe(json_str)

然后在模板中:

{% load jsonify %}
{{ value|jsonify }}

关于javascript - 从 Django 获取一个列表到 Javascript 作为一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52999355/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com