我正在用烧瓶构建一个表单,下面是我的烧瓶服务器的简化版本
app = Flask(__name__)
@app.route("/", methods = ["POST", "GET"])
def main_page():
if request.method == "POST":
# some cool stuff
return render_template("main.html")
if __name__ == "__main__":
app.debug = True
app.run()问题是,当用户提交表单时,它会重新呈现页面,跳到页面的顶部。这让用户体验有点糟糕。如何在不重新呈现整个页面的情况下获取表单的数据?
发布于 2022-02-27 16:36:07
如果您想提交表单数据,但不想完全重新呈现页面,那么您唯一的选择就是使用阿贾克斯。
在下面的示例中,使用取API发送表单数据。服务器上的处理基本上保持不变,因为表单数据是以相同格式提交的。
但是,由于这里通常有JSON格式的响应,所以我建议将端点外包,这样HTML和JSON路由之间就有了分离。
from flask import (
Flask,
jsonify,
render_template,
request
)
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/upload', methods=['POST'])
def upload():
# Same cool stuff here.
print(request.form.get('data'))
return jsonify(message='success')<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Index</title>
</head>
<body>
<form name="my-form" method="post">
<input type="text" name="data" />
<input type="submit" />
</form>
<script type="text/javascript">
(uri => {
// Register a listener for submit events.
const form = document.querySelector('form[name="my-form"]');
form.addEventListener('submit', evt => {
// Suppress the default behavior of the form.
evt.preventDefault();
// Submit the form data.
fetch(uri, {
method: 'post',
body: new FormData(evt.target)
}).then(resp => resp.json())
.then(data => {
console.log(data);
// Handle response here.
});
// Reset the form.
evt.target.reset();
});
})({{ url_for('upload') | tojson }});
</script>
</body>
</html>https://stackoverflow.com/questions/71285841
复制相似问题