python - 在 javascript Flask 中传递字典列表

Leg*_*ggo 4 javascript python dictionary flask

我知道如何将一个变量从 Flask (python) 传递给我的模板 html 文件{{data}}。但是,我无法在 javascript 中访问列表中的每个字典元素及其各自的键值对。

启动文件

def func1():
        data = filter() #returns a list of dictionaries

    return render_template("template1.html", data=data)
Run Code Online (Sandbox Code Playgroud)

模板1.html

<html>
  <head>
  .....
  </head>
  <body>
    <p>This is html: {{data}}</p>

    <script type="text/javascript" src="{{url_for('static', filename='js/add.js') }}"></script>
    <script type="text/javascript">
    myvar = '{{data}}';
    document.write(myvar);

    </script>
  </body>

</html>
Run Code Online (Sandbox Code Playgroud)

添加.js

//code to be written here
Run Code Online (Sandbox Code Playgroud)

myvar并且This is html:都输出整个字典列表。我已经尝试过,myvar[0][出于某种原因只是输出。我也做过:

myvar = '{{data|tojson}}';
var parsed = JSON.parse(myvar);
document.write(parsed[0]);
Run Code Online (Sandbox Code Playgroud)

但输出[object Object].

kra*_*ski 9

通过放置data单引号,您正在创建一个字符串。要将 Python 数据类型导入 JavaScript,请使用{{ data | tojson }}.

var parsed = JSON.parse('{{data | tojson}}');
Run Code Online (Sandbox Code Playgroud)

您可能需要使用safe过滤器对输出进行转义。查看更多关于使用 Jinja 将数据作为 JSON 对象从 Python 发送到 Javascript