简体   繁体   English

将 JSON 数据从 Flask 传递到 JavaScript

[英]Passing JSON data from Flask to JavaScript

I am trying to pass a JSON data from flask to JavaScript.我正在尝试将 JSON 数据从 flask 传递到 JavaScript。

The code I tried is from:我尝试的代码来自:


The steps below are what I did:以下步骤是我所做的:

  1. I first got my data from postgreSQL in Python我首先从 Python 中的 postgreSQL 得到我的数据
  2. I transformed the data format from DataFrame to JSON我将数据格式从 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. I modified @Ilya V. Schurov's code我修改了@Ilya V. Schurov 的代码
app = Flask(__name__)

@app.route('/')

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

app.run()

And this is my index.html file:这是我的 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>


However, it kept showing the error但是,它一直显示错误

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

And the webpage( http://127.0.0.1:5000/ ) showing:网页( 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.

I spent almost 2 days on this problem, passing the json data to the JavaScript, but still don't know how to solve this... Could anyone give me some suggestion on this?我在这个问题上花了将近 2 天的时间,将 json 数据传递给 JavaScript,但仍然不知道如何解决这个问题......有人能给我一些建议吗?

In the template, you are using the variable json2 :在模板中,您正在使用变量json2

{{ json2 | tojson | safe}}

but, when rendering, you are passing in variable data :但是,在渲染时,您传递的是可变data

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

Replace json2 with data in your template:json2替换为模板中的data

{{ data | tojson | safe }}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM