0
我有一個簡單的代碼Flask
。我有一個網站有4個按鈕,當按下後發送POST到Flask
並返回相同的頁面,但用另一種顏色收緊的按鈕。每個按鈕的狀態都存儲在布爾數組中。
這是Flask
代碼:重新加載頁面重新發送數據
import numpy as np
from flask import Flask, request, render_template
app = Flask(__name__)
states = np.array([0, 0, 0, 0], dtype=bool)
@app.route('/control', methods=['GET', 'POST'])
def control():
if request.method == 'POST':
val = int(request.form['change rele state'])
states[val] = not states[val]
return render_template('zapa.html', states=states)
else:
return render_template('zapa.html', states=states)
if __name__ == '__main__':
app.run(debug=True)
和頁面:
{% extends "layout.html" %}
{% block content %}
<h2>Control</h2>
<p>Botones</p>
<p>{{ states }}</p>
<form action="/control" method="POST">
{% for state in states %}
{% if state == True %}
<button class="btn btn-primary" type="submit" name="change rele state" value="{{ loop.index0 }}">Enchufe {{ loop.index }} Off</button>
{% endif %}
{% if state == False %}
<button class="btn btn-danger" type="submit" name="change rele state" value="{{ loop.index0 }}">Enchufe {{ loop.index }} On</button>
{% endif %}
{% endfor %}
</form>
{% endblock %}
的問題是,按重新加載頁面,彷彿按下按鈕時發送。爲什麼?我如何避免這種情況?