提问人:Alex K 提问时间:10/6/2023 最后编辑:Alex K 更新时间:10/6/2023 访问量:48
使用 ajax 进行 Python 在线数据修改
Python online data modification using ajax
问:
包含 FORM 和 SELECT 的 Python3(FLASK) 应用程序。
在 SELECT 中选择特定位置时,FORM 的内容应更改,而无需重新加载页面。
我想为此使用AJAX,但是在Python将数组返回到页面后,我不明白如何更改页面上的数据。
Python 使用 FLASK 接收数据并呈现布局
@app.route('/', methods=['POST', 'GET'])
def index():
try:
for i in DB.check_connect():
if i[0] == 1:
get_ratio = DB.get_ratio()
get_office_group = DB.get_office_group()
get_rates_for_current_office = DB.get_rates_for_current_office(0)
lenth_rates = len(get_rates_for_current_office)
#We get the value from the selected SELECT and return an array of new values.
if request.method == "POST":
id = request.form['id']
get_rates_for_current_office = DB.get_rates_for_current_office(id)
return get_rates_for_current_office
else:
print('Cannot connect DB')
resp = make_response(render_template('index.html', get_ratio=get_ratio, get_office_group=get_office_group, get_rates_for_current_office = get_rates_for_current_office, lenth_rates = lenth_rates))
return resp
except Exception as error:
print("An exception occurred:", error)
return render_template('login.html')
HTML 页面
<select class="form-select mt-3" name="office_group">
{% for item in get_office_group %}
<option data-id="{{ item[0] }}" value="{{ item[0] }}">{{ item[1] }}</option>
{% endfor %}
</select>
...............
<tbody>
{% for i in range(0, lenth_rates) %}
<tr>
<td>{{ get_ratio[i][0] }}</td>
<td>{{ get_ratio[i][3] }} {{ get_ratio[i][1] }}/{{ get_ratio[i][2] }}</td>
<td><input class="form-control" name="buy_{{ get_ratio[i][4] }}" value='{{ get_rates_for_current_office[i][0] }}'/></td>
<td><input class="form-control" name="sell_{{ get_ratio[i][4] }}" value='{{ get_rates_for_current_office[i][1] }}'/></td>
<td></td>
</tr>
{% endfor %}
</tbody>
AJAX 将 SELECT 中选择的值传递给 Python。
<script>
$(document).ready(function(){
$('select').change(function(){
$ids = $(this).children('option:selected').data('id')
$.ajax({
url: '/',
data: {id:$ids},
type: 'POST',
success: function(get_rates_for_current_office){
console.log(get_rates_for_current_office);
},
error: function(error){
console.log(error);
}
});
});
});
</script>
是否可以在不使用 Python(最好)或其他模块重新加载的情况下对页面上的数据进行在线更改?
答: 暂无答案
评论
login.html
select