【问题标题】:how to send JSON to HTML file using flask?如何使用烧瓶将 JSON 发送到 HTML 文件?
【发布时间】:2020-10-05 11:41:40
【问题描述】:

我是编码的初学者,但我被困在最后的结束:| 我正在使用 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 = 197.1.

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

谢谢!

【问题讨论】:

    标签: javascript python json flask


    【解决方案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 以后兼容。

    【讨论】:

    • {{result['f']}} 太棒了!
    【解决方案2】:

    两个建议:

    您将结果序列化为 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 函数传递对象时访问它们。在您的情况下,&lt;center&gt;&lt;h1&gt;Final = {{result['f]}}&lt;/h1&gt;&lt;/center&gt; 应该可以完成这项工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-26
      • 2023-04-02
      • 1970-01-01
      • 2020-05-14
      • 1970-01-01
      • 2021-10-11
      • 1970-01-01
      • 2023-03-11
      相关资源
      最近更新 更多