我正在用燒瓶構建一個表單,下面是我的燒瓶服務器的簡化版本
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()
問題是當用戶提交表單時它會重新渲染頁面,跳轉到頁面頂部。這使得用戶體驗有點糟糕。如何在不重新渲染整個頁面的情況下獲取表單的資料?
uj5u.com熱心網友回復:
如果您想提交表單資料,但又不想完全重新渲染頁面,您唯一的選擇是使用AJAX。
在以下示例中,表單資料是使用Fetch 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://www.uj5u.com/gongcheng/435986.html
