You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Bootstrap确认模态框点击确认后调用带参数的Ajax函数?

解决Bootstrap确认模态框点击Yes后调用Ajax的问题

没问题,我来帮你搞定这个需求!核心思路是先把remove函数接收的参数暂存起来,等用户确认点击"Yes"后,再用这个参数发起Ajax请求。下面是具体的实现步骤和完整代码:

1. 暂存参数并打开模态框

修改你的remove函数,在打开模态框的同时,把传入的parameter存储到模态框元素的自定义data属性中,这样后续点击确认按钮时就能轻松拿到这个参数:

function remove(parameter) {
  // 将参数存储到模态框的data属性中
  $("#remove-modal").data("target-parameter", parameter);
  // 打开模态框
  $("#remove-modal").modal('show');
}

2. 绑定"Yes"按钮的点击事件

在页面加载完成后,给模态框的"Yes"按钮绑定点击事件,在事件里取出之前存储的参数,执行Ajax请求:

$(document).ready(function() {
  // 监听Yes按钮的点击事件
  $("#modal-btn-si").click(function() {
    // 从模态框中取出存储的参数
    const parameter = $("#remove-modal").data("target-parameter");
    
    // 执行Ajax请求
    $.ajax({
      url: "/your-delete-api", // 替换成你的实际后端接口地址
      type: "DELETE", // 根据后端要求选择请求方式,比如POST/DELETE
      data: { id: parameter }, // 把参数传给后端,键名按需修改
      success: function(response) {
        // 请求成功后的处理,比如提示删除成功、刷新列表
        alert("删除操作已完成!");
        // 关闭模态框
        $("#remove-modal").modal('hide');
        // 这里可以添加刷新页面或更新列表的逻辑
      },
      error: function(xhr, status, error) {
        // 请求失败后的处理
        alert("删除失败,请稍后重试!");
        $("#remove-modal").modal('hide');
      }
    });
  });
});

3. 模态框HTML保持不变

你的模态框HTML代码不需要修改,直接保留即可:

<div class="modal fade" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true" id="remove-modal"> 
  <div class="modal-dialog modal-sm"> 
    <div class="modal-content"> 
      <div class="modal-header"> 
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> 
        <h4 class="modal-title" id="myModalLabel">Do you want to remove this item?</h4> 
      </div> 
      <div class="modal-footer"> 
        <button type="button" class="btn btn-default" id="modal-btn-si">Yes</button> 
        <button type="button" class="btn btn-primary" id="modal-btn-no" data-dismiss="modal">No</button> 
      </div> 
    </div> 
  </div> 
</div>

小提示

  • 记得把Ajax中的url替换成你实际的后端接口地址
  • 根据后端接口要求调整type(比如用DELETE更符合REST规范)和data的格式
  • 如果想要更美观的提示,可以用Bootstrap的Alert组件代替原生alert()函数

内容的提问来源于stack exchange,提问作者User1v0

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:19:59