我有一个HTML表单,该表单向我的flask应用程序发出POST请求,并且flask应用程序返回一个字符串。我想在同一HTML页面上显示字符串。
index.html
<iframe name="frame" class="hidden"></iframe>
<form action="/upload" target="frame" method="POST">
<input type="text" name="text" />
<button type="submit">Submit</button>
</form>
<p id="text"></p>
注意:隐藏的<iframe>
被保留为target
,以便页面不会重定向。
app.py
from flask import Flask, request, render_template
app = Flask(__name__)
@app.route('/')
def my_form():
return render_template('index.html')
@app.route('/upload', methods=['POST'])
def my_form_post():
text = request.form['text']
processed_text = text.upper()
# Some internal stuff with processed text
return processed_text
我想在processed_text
中显示<p id="text"></p>
我是烧瓶新手。我该怎么办?
答案 0 :(得分:0)
您可能想学习HTML如何使用jinja2读取变量。您要查找的代码应该是。我还添加了一个if示例,因此您也可以检查其语法:
index.html
<iframe name="frame" class="hidden"></iframe>
<form action="/upload" target="frame" method="POST">
<input type="text" name="text" />
<button type="submit">Submit</button>
</form>
{% if processed_text %}
<p id="text">{{ processed_text }}</p>
{% endif %}
这样,{{}}中的内容将在寻找变量。但是,仅此还不够。从路线返回时,您可以对不同的路线使用相同的模板,因此在上载时渲染相同的模板并将其传递给processed_text变量将使您的页面正确显示文本。请注意,如果不从应用程序中传递变量值,否则可能会出错,因此不应在模板中使用变量。在这种情况下,由于除非定义了该变量,否则包含<p id="text">{{ processed_text }}</p>
的行甚至都不会加载,因此您应该没有问题,但请记住这一点。
app.py
from flask import Flask, request, render_template
app = Flask(__name__)
@app.route('/')
def my_form():
return render_template('index.html')
@app.route('/upload', methods=['POST'])
def my_form_post():
text = request.form['text']
processed_text = text.upper()
# Some internal stuff with processed text
return render_template('index.html', processed_text=processed_text)
编辑:正如评论中提到的那样,回答时我没有注意到,当您将iframe定位为表单时,您并没有停止重新加载页面,而是加载了该页面再次在框架内。 Flask的路由不是解决此问题的最佳方法,因此您只需删除上传路由,并通过像这样修改它,即可完全从HTML文件上传文本。我也取出了框架,因为它不再需要:
<head>
<script>
document.addEventListener('DOMContentLoaded', () => {
document.querySelector('#upload').onsubmit = () => {
const text = document.querySelector('#input').value;
document.querySelector('#text').innerHTML = text.toUpperCase(text);
return false;
};
});
</script>
</head>
<body>
<form id="upload">
<input type=text id="input">
<button type="submit">Submit</button>
</form>
<p id="text"></p>
</body>