簡體   English   中英

如何使用flask將JSON發送到HTML文件?

[英]how to send JSON to HTML file using flask?

我是編碼的初學者,我被困在最后的閉幕式上:| 我正在使用 python 2.7 這是我的serever.py

from flask import Flask, render_template,request,jsonify
import requests
import json
import new

app = Flask(__name__)

#serve homepage
@app.route('/', methods=["GET","POST"])
def homepage():
   return render_template('page2.html')
 
@app.route('/page3.html', methods=["POST"])
def result_matchup():
    h= request.form['h']
    a= request.form['a']
    l= request.form['l']
    p= request.form['p']
    result = json.dumps(new.calc(h,a,l,p))
    
    return render_template('page3.html',result=result)  


if __name__ == "__main__":
    app.run(debug=True)

當我要求return result以檢查自己時,這是輸出:

{"f": 197.1, "k": 196}

這是我的 page3.html:


<!DOCTYPE html>
<html>
<head>

</head>
<body>

    <center><h1>Final = {{f}}</h1></center>

</body>
</html>

所有這些的輸出是"Final = " ,而我期望Final = 197.1。

我究竟做錯了什么? 有什么幫助嗎?

謝謝!

我假設new.calc返回一個字典。 在傳遞給您的模板之前,無需使用json.dumps進行字符串化。 因此,請嘗試:

result = new.calc(h,a,l,p)

result現在應該是一個字典,鍵為'f''k'

因此,在模板中你應該訪問這個字典,就像你在 python 中一樣:

<center><h1>Final = {{result['f']}}</h1></center>

我還建議使用更高版本的 python,因為現在不支持2.7 ,並且盡早進行此更改將防止您必須使已經編寫的代碼與3.x兼容。

兩個建議:

您將結果序列化為 JSON 寫入result = json.dumps(new.calc(h,a,l,p)) 但是,您應該直接將 Python 對象傳遞給render_template 事實上,這是 Jinja 模板的優勢之一:您不需要傳遞 JSON,但您可以直接處理 Python 對象。 所以只需寫result = new.calc(h,a,l,p)

其次,在 Jinja 模板中,您必須在通過render_template函數傳遞對象時訪問它們。 在您的情況下, <center><h1>Final = {{result['f]}}</h1></center>應該可以完成這項工作。

暫無
暫無

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

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