尝试使用Flask将嵌套列表通过JSON传递给JS

huangapple go评论61阅读模式
英文:

Trying to pass a nested list with JSON to JS with Flask

问题

以下是翻译的内容:

问题是我将参数传递给JavaScript的方式如下:链接

变量"chatlist"是问题所在。该变量的值是

[[{"user": "lol"}, {"msg": "lol has created this chat."}], [{"user": "lol"}, {"msg": "lol"}]]

但是当我尝试通过此代码访问该变量时:链接,它最终看起来像

[[{"user": "lol"}, {"msg": "lol has created this chat."}], [{"user": "lol"}, {"msg": "lol"}]]

我期望的是,在我的Python代码和我的JavaScript中,我都获得

[[{"user": "lol"}, {"msg": "lol has created this chat."}], [{"user": "lol"}, {"msg": "lol"}]]

作为标记为"chatList"的变量的值。此值还需要是"可解析"的(不确定是否是正确的词)。我需要能够访问列表的所有元素以及每个元素中每个字典的所有键和值。

英文:

The problem is I'm passing my argument to the Javascript like this: link.

The variable "chatlist" is the problem. The value of that variable is

[[{"user": "lol"}, {"msg": "lol has created this chat."}], [{"user": "lol"}, {"msg": "lol"}]]

But when I try to access that variable through this code: link, it ends up looking like

[[{"user": "lol"}, {"msg": "lol has created this chat."}], [{"user": "lol"}, {"msg": "lol"}]]

What I'm expecting is in both my Python code and my Javascript, I get

[[{"user": "lol"}, {"msg": "lol has created this chat."}], [{"user": "lol"}, {"msg": "lol"}]]

as the value of the variable labelled "chatList". This value also needs to be "parsable" (not sure if that's the right word). I need to be able to access all elements of the list and all keys and values of each dictionary in each element.

答案1

得分: 1

将列表原样传递给 render_template

return render_template("chat.html", chatlist=chatInfo, pin=pin)

在模板中,你可以使用 Jinja 过滤器 tojson

var chatList = {{ chatlist | tojson }};
console.log(chatList);
英文:

Pass the list as is to render_template.

return render_template("chat.html", chatlist=chatInfo, pin=pin)

In the template you can use the jinja filter tojson.

var chatList = {{ chatlist | tojson }};
console.log(chatList);

答案2

得分: 0

似乎双引号已经被HTML转义了。

我会通过使用JavaScript的decodeURI()方法来解决这个问题。

英文:

It looks like the double quotes are getting HTML escaped.

I would solve this by using Javascript's decodeURI() method.

huangapple
  • 本文由 发表于 2023年2月19日 04:19:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/75496152.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定