首页 > 解决方案 > 如何使用烧瓶将 JSON 发送到 HTML 文件?

问题描述

我是编码的初学者,我被困在最后的关门处:| 我正在使用 python 2.7 这是我的server.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。

我究竟做错了什么?有什么帮助吗?

谢谢!

标签: javascriptpythonjsonflask

解决方案


我假设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以后兼容。


推荐阅读