簡體   English   中英

將 JSON 數據從 Flask 傳遞到 JavaScript

[英]Passing JSON data from Flask to JavaScript

我正在嘗試將 JSON 數據從 flask 傳遞到 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,但仍然不知道如何解決這個問題......有人能給我一些建議嗎?

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

{{ json2 | tojson | safe}}

但是,在渲染時,您傳遞的是可變data

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

json2替換為模板中的data

{{ data | tojson | safe }}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM