如何用AJAX调用Flask接口更新表单的价格与库存信息?
实现双下拉框联动获取价格库存并更新表单
关键修改与实现步骤
- 补全表单元素:添加价格和库存的只读输入框,用于展示接口返回的数据
- 完善事件绑定:修正下拉框的
onchange事件调用方式,确保触发函数执行 - 添加参数校验:只有当两个下拉框都选中有效选项时,才发送AJAX请求
- 解析返回数据:处理接口返回的
price:stock格式字符串,更新对应输入框
完整前端代码
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script type=text/javascript> function getPrices() { // 获取两个下拉框的选中值 const country = $('#country').val(); const service = $('#service').val(); // 校验是否已完成全部选择 if (!country || !service) { // 未完全选择时清空输入框,避免残留旧数据 $('#price-input').val(''); $('#stock-input').val(''); return; } // 发送AJAX请求到Flask接口 $.ajax({ url: '/getPrices', type: 'GET', data: { country: country, service: service }, success: function(response) { // 解析返回的price:stock格式数据 const [price, stock] = response.split(':'); // 更新价格和库存输入框 $('#price-input').val(price); $('#stock-input').val(stock); }, error: function(xhr, status, error) { console.error('请求失败:', error); // 请求失败时清空输入框 $('#price-input').val(''); $('#stock-input').val(''); } }); } </script> {% extends "_base.html" %} {% block content %} {% if current_user.is_authenticated %} <h3 class="text-center">Welcome {{current_user.email}}!</h3> {% else %} <h3 class="text-center">Price List</h3> {% endif %} <br> <div class="form-group"> <form action="" method="post"> <div class="input-group mb-3-center" style="display: flex;justify-content: center;"> <div class="input-group-prepend"> <label for="country">Country</label> <br> <select class="selectpicker" title="Choose a country..." data-live-search="true" id="country" onchange="getPrices()"> <option value="">请选择</option> <option value="uk">uk</option> <option value="2">Two</option> <option value="3">Three</option> </select> <br> <br> <label for="service">Service</label> <br> <select class="selectpicker" title="Choose a service..." data-live-search="true" id="service" onchange="getPrices()"> <option value="">请选择</option> <option value="1">one</option> <option value="2">Two</option> <option value="3">Three</option> </select> <br> <br> <label for="price-input">Price</label> <span class="input-group-text" style="font-size: medium;">$</span> <input type="text" id="price-input" readonly class="form-control"> <br> <label for="stock-input">Stock</label> <span class="input-group-text" style="font-size: medium;">-</span> <input type="text" id="stock-input" readonly class="form-control"> <br> </div> </div> </form> {% endblock %}
Flask后端接口示例
from flask import Flask, request app = Flask(__name__) @app.route('/getPrices', methods=['GET']) def get_prices(): country = request.args.get('country') service = request.args.get('service') # 模拟业务逻辑:根据country和service查询价格库存 if country and service: # 实际场景中从数据库/第三方接口获取真实数据 return "0.5:1000" else: # 参数不全时返回错误状态码 return "", 400 if __name__ == '__main__': app.run(debug=True)
核心注意点
- 参数校验:前后端双重校验,避免因参数缺失导致接口报错
- 数据安全:将价格和库存输入框设置为
readonly,防止用户手动修改 - 异常处理:AJAX请求失败时清空输入框,避免展示无效旧数据
内容的提问来源于stack exchange,提问作者big boss
相关产品推荐
相关产品推荐

