當單擊相應的按鈕時,我試圖將 for 回圈中生成的 jinja 變數傳遞給后端。當我單擊任何按鈕時,將傳遞串列中的第一個值。我試過的代碼是
代碼
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/search_tag', methods=["GET", "POST"])
def search_tag():
if request.method == 'POST':
print("hi")
tag_x = request.form['rawtext']
print(tag_x)
return render_template('index.html', messg = "SUCCESS")
else:
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
html代碼
<!DOCTYPE html>
<html>
<head>
<title>Test App</title>
</head>
<body>
<form method="POST" action="{{ url_for('search_tag')}}">
<div id ="result">
<p style="color:red">
{% for i in ["hello","hi","travel","goal"] %}
<li>{{ i }}
<input type="hidden" id="rawtext" name="rawtext" value="{{ i }}">
<input type="submit" name="submit" value="click" class="btn btn-info">
</li>
{% endfor %}
</p><br>
</div>
</form>
{{ messg }}
</body>
</html>
</body>
</html>
提前致謝
uj5u.com熱心網友回復:
我通過使用單選按鈕和@Ioannis Skaltsas 的建議解決了(感謝您的建議。如果有更好的方法,請建議像 ajax 或其他東西)。更正的代碼是 --->
<!DOCTYPE html>
<html>
<head>
<title>Test App</title>
</head>
<body>
<form method="POST" action="{{ url_for('search_tag')}}">
<div id ="result">
<p style="color:red">
{% for i in ["hello","hi","travel","goal"] %}
<input type="radio" id="rawtext" name="rawtext" value="{{ loop.index }}">{{ i }} <br>
{% endfor %}
<input type="submit" name="submit" value="click" class="btn btn-info">
</p><br>
</div>
</form>
{{ messg }}
</body>
</html>
</body>
</html>
由于最初串列是在python代碼中生成的(這里靜態用于html代碼),基于使用按鈕提交的選定回圈索引,我可以從python端的串列中獲取值。
uj5u.com熱心網友回復:
在你的 html 中做這樣的事情:
<input type="hidden" id="rawtext" name="rawtext{{loop.index}}" value="{{ i }}">
您還需要在燒瓶代碼中使用 for 回圈來遍歷所有名稱。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/377670.html
