如何在 Flask 上动态发送来自 HTML 的值?
How to send dynamically a value from HTML on Flask?
我正在从 MySQL 数据库获取值,我可以在 HTML 上显示它,但是当我尝试发送发送值时,我总是得到第一个值。
表格如下:
<form action="/delete_country" method="post">
<table>
<tr>
{% for header in headers %}
<th>{{header}}</th>
{% endfor %}
</tr>
{% for row in countries %}
<tr>
{% for cell in row %}
<td>{{cell}}</td>
{% endfor %}
<td><input type="text" name="id_country" value="{{row[0]}}"></td>
<td><button type="submit">Delete</button></td>
</tr>
{% endfor %}
</table>
</form>
这是 server.py 上的函数,它总是 return 第一个值
@app.route("/")
@app.route("/index")
def index():
headers = ("CODE", "Name", "Continent", "code2", "Delete")
countries = controller.get_coutries()
return render_template("index.html", headers=headers, countries=countries)
@app.route("/delete_country", methods=['POST'])
def delete_country():
id_country = request.form['id_country']
return id_country
controller.py
def get_coutries():
con = get_connection()
countries = []
with con.cursor() as cursor:
cursor.execute("select code, name, continent from country")
countries = cursor.fetchall()
con.close()
return countries
如果我点击 Antartica,代码是 ATA 它会 return ABW。
<td><input type="text" name="id_country" value="{{row[0]}}"></td>
您在每个循环中设置相同的 ID,因此您有很多具有相同 ID 的输入,这就是您获得第一个值的原因
我更喜欢这些东西的链接而不是表格,并在 flask 端使用 url 参数。
<a href="http://yourip/delete_country/{{row[0]}}"></a>
@app.route("/delete_country/<id>", methods=['POST'])
def delete_country(id):
id_country = id
return id_country
我正在从 MySQL 数据库获取值,我可以在 HTML 上显示它,但是当我尝试发送发送值时,我总是得到第一个值。
表格如下:
<form action="/delete_country" method="post">
<table>
<tr>
{% for header in headers %}
<th>{{header}}</th>
{% endfor %}
</tr>
{% for row in countries %}
<tr>
{% for cell in row %}
<td>{{cell}}</td>
{% endfor %}
<td><input type="text" name="id_country" value="{{row[0]}}"></td>
<td><button type="submit">Delete</button></td>
</tr>
{% endfor %}
</table>
</form>
这是 server.py 上的函数,它总是 return 第一个值
@app.route("/")
@app.route("/index")
def index():
headers = ("CODE", "Name", "Continent", "code2", "Delete")
countries = controller.get_coutries()
return render_template("index.html", headers=headers, countries=countries)
@app.route("/delete_country", methods=['POST'])
def delete_country():
id_country = request.form['id_country']
return id_country
controller.py
def get_coutries():
con = get_connection()
countries = []
with con.cursor() as cursor:
cursor.execute("select code, name, continent from country")
countries = cursor.fetchall()
con.close()
return countries
如果我点击 Antartica,代码是 ATA 它会 return ABW。
<td><input type="text" name="id_country" value="{{row[0]}}"></td>
您在每个循环中设置相同的 ID,因此您有很多具有相同 ID 的输入,这就是您获得第一个值的原因
我更喜欢这些东西的链接而不是表格,并在 flask 端使用 url 参数。
<a href="http://yourip/delete_country/{{row[0]}}"></a>
@app.route("/delete_country/<id>", methods=['POST'])
def delete_country(id):
id_country = id
return id_country