仅在Bootstrap模态框显示时触发HTMX GET请求
解决Bootstrap模态框打开时才触发HTMX请求的问题
问题分析
你当前代码在页面加载时就会触发所有模态框内HTMX的GET请求,核心原因是hx-trigger="load target:#modal-{{product.CODIGO}}"的逻辑不符合需求:HTMX的load触发器是在元素本身加载完成时触发,而非模态框被打开时。即使模态框初始隐藏,DOM元素已经存在,所以HTMX依然会执行请求。
Bootstrap模态框提供了shown.bs.modal事件,这个事件会在模态框完全显示给用户后触发,正好匹配你“打开时加载数据”的需求。
解决方案
将HTMX的触发器修改为监听对应模态框的shown.bs.modal事件,同时可添加hx-once="true"确保每个模态框只加载一次数据(可选,根据业务需求调整)。
修改后的代码片段
{% for _, product in products_table.items() %} <div class="modal fade" tabindex="-1" id="modal-{{product.CODIGO}}" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">{{ product.PRODUTO }}</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <table class="table" id="product-detail"> <thead> <tr> <th scope="col">Loja</th> <th scope="col">Estoque</th> </tr> </thead> <tbody> {% for store in toy_store_list %} <tr id="tr-{{ store.alias }}"> <td>{{ store.name }}</td> <td> <span style='font-weight: bold' hx-trigger="shown.bs.modal from:#modal-{{product.CODIGO}}" hx-get="{{ url_for('product.get_product_stock', store=store.alias, search_term=product.CODIGO) }}" hx-swap="innerHTML" hx-target="this" hx-once="true"> <!-- 可选:仅加载一次数据 --> <div class="spinner-border spinner-border-sm htmx-indicator" role="status"></div> </span> </td> </tr> {% endfor %} </tbody> </table> </div> </div> </div> </div> {% endfor %}
关键修改点
- 替换
hx-trigger为shown.bs.modal from:#modal-{{product.CODIGO}}:明确指定当对应ID的模态框触发shown.bs.modal事件时,才执行当前元素的HTMX请求。 - 添加
hx-once="true"(可选):避免每次打开模态框都重复调用接口,仅在第一次打开时加载数据。
额外说明
如果使用Bootstrap v5.x,shown.bs.modal事件逻辑正常;若为旧版本,需确认事件名称匹配。如果需要在模态框关闭后清空数据,可结合Bootstrap的hidden.bs.modal事件,通过HTMX或JS重置内容。
内容的提问来源于stack exchange,提问作者Thomaz Yuji
相关产品推荐
相关产品推荐

