首页 > 解决方案 > 将 JSON 数据从 Flask 传递到 JavaScript

问题描述

我正在尝试将 JSON 数据从烧瓶传递到 JavaScript。

我尝试的代码来自:


以下步骤是我所做的:

  1. 我首先在 Python 中从 postgreSQL 获取数据
  2. 我将数据格式从 DataFrame 转换为 JSON
    
def to_json2(df,orient='split'):
    df_json = df.to_json(orient = orient, force_ascii = False)
    return json.loads(df_json)


def to_fronrend(data):
    return {"data": data}

json2 = to_json2(df)
json2 = to_fronrend(json2) 
  1. 我修改了@Ilya V. Schurov 的代码
app = Flask(__name__)

@app.route('/')

def hello_world():
    data = json2
    return render_template("index.html", data = data)

app.run()

这是我的 index.html 文件:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title> Hello </title>
</head>
    
<body>
    <p>Hello, <span id="username"></span></p>
    
    <script>
    var data = JSON.parse('{{ json2 | tojson | safe}}');
    document.getElementById('username').innerHTML = data.Name + " " + data.Gatein;
    </script>

    
    </body>
</html>


但是,它一直显示错误

TypeError: Object of type Undefined is not JSON serializable
127.0.0.1 - - [18/Dec/2020 22:14:14] "GET / HTTP/1.1" 500 -

网页(http://127.0.0.1:5000/)显示:

Internal Server Error The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.

我在这个问题上花了将近 2 天的时间,将 json 数据传递给 JavaScript,但仍然不知道如何解决这个问题......有人可以给我一些建议吗?

标签: javascriptpythonjsonflask

解决方案


在模板中,您正在使用变量json2

{{ json2 | tojson | safe}}

但是,在渲染时,您正在传递变量data

return render_template("index.html", data=data)

在您的模板中替换json2为:data

{{ data | tojson | safe }}

推荐阅读