首页 > 解决方案 > 如何使 Flask 在 HTML 中运行函数并在同一页面上打印结果?

问题描述

我一直在尝试使用我之前编写的脚本将阿拉伯数字转换为罗马数字。用户输入数字,我的脚本将它们转换为罗马数字。脚本运行良好,但我试图将其嵌入网页并没有按预期工作。我在谷歌上搜索了解决方案,每个人都告诉我需要从表单中获取价值,我这样做了:

                <form action="toroman" method="POST">
                    <input type="number" name="arabic" onChange="toroman(this.value)" oninput="toroman(this.value)">
                    <p>{{ romanfinal }}</p>
                </form>

这是我的 server.py 应该打印出同一页面的编号,但它没有这样做,而是当我在提交值时按“Enter”时,它会创建一个新页面并显示正确的答案。

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route("/")
def index():
    return render_template("index.html")


@app.route("/toroman", methods=['POST'])
def toroman():
    arabic = request.form['arabic']
    # some unnecessarily numerous lines of code that basically turn Arabic-system number to Roman system
    return romanfinal


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

这就像它真正起作用的唯一一次,当我尝试将其更改为其他内容时,它只会给我错误。请告诉我我到底有什么不明白的。

标签: pythonhtmlflask

解决方案


您的toroman():函数应返回带有参数的 index.html:

@app.route("/toroman", methods=['POST'])
def toroman():
    arabic = request.form['arabic']
    # some unnecessarily numerous lines of code that basically turn Arabic-system number to Roman system
    return render_template("index.html", data = romanfinal)

然后,您可以data像这样在 HTML 顶级中使用该值:{{data}}


推荐阅读