如何让 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)

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


慕慕森
浏览 196回答 2
2回答

喵喵时光机

你的toroman():函数应该返回带有参数的 index.html :@app.route("/toroman", methods=['POST'])def toroman():&nbsp; &nbsp; arabic = request.form['arabic']&nbsp; &nbsp; # some unnecessarily numerous lines of code that basically turn Arabic-system number to Roman system&nbsp; &nbsp; return render_template("index.html", data = romanfinal)data然后你可以像这样在你的 HTML 顶层使用这个值:{{data}}

qq_遁去的一_1

烧瓶from flask import Flask, render_template, request, jsonifyapp = Flask(__name__)@app.route("/")&nbsp; &nbsp; def index():return render_template("index.html")@app.route("/toroman", methods=['POST'])def toroman():&nbsp; &nbsp; arabic = request.data['arabic']&nbsp; &nbsp; #pass arabic into your translation function&nbsp; &nbsp; translation = translate()&nbsp; &nbsp; #return JSON response to AJAX&nbsp; &nbsp; return jsonify(translation = translation)if __name__ == "__main__":&nbsp; &nbsp; app.run(debug=True)JS$(document).ready(function(){&nbsp; document.getElementById('toroman_form').addEventListener('keyup', function() {&nbsp; &nbsp;$.ajax({&nbsp; &nbsp; &nbsp; &nbsp; type: 'POST',&nbsp; &nbsp; &nbsp; &nbsp; url: '/toroman', //flask route to which data is sent&nbsp; &nbsp; &nbsp; &nbsp; data: $('#arabic').val(), // input field value&nbsp; &nbsp; &nbsp; &nbsp; contentType:'application/json; charset=utf-8',&nbsp; &nbsp; &nbsp; &nbsp; dataType: "json",&nbsp; &nbsp; &nbsp; &nbsp; success: function(data) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; translation = data.translation //response received from flask&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $('#translated').text(translation) //display translation in html <p> tag&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; error: function() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert("Transaction Failed");&nbsp; &nbsp; &nbsp; }&nbsp; });});}HTML<form id="toroman_form">&nbsp; &nbsp; <input type="number" id="arabic">&nbsp; &nbsp; <p id="translated"><!--translation is dislayed here--></p></form>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python