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

如何将管理Bootstrap Modal的jQuery代码转为原生JavaScript适配Symfony开发环境

jQuery代码转原生JavaScript实现方案

以下是和你给出的jQuery代码功能完全等效的原生JS实现:

// 等效 $(function() {}),监听DOM加载完成
document.addEventListener('DOMContentLoaded', function() {
  // 绑定所有.exercice-class按钮的点击事件
  document.querySelectorAll('.exercice-class').forEach(button => {
    button.addEventListener('click', function(e) {
      e.preventDefault();
      // 获取data-id属性,等效$(this).data('id')
      const id = this.dataset.id;
      const url = `../exercice-class/${id}/`;
      
      // 等效$.get,用fetch实现异步请求
      fetch(url)
        .then(response => response.text())
        .then(data => {
          // 等效$(".container-fluid").append(data)
          document.querySelector('.container-fluid').insertAdjacentHTML('beforeend', data);
          // 打开模态框,调用Bootstrap原生API
          const showModal = new bootstrap.Modal(document.getElementById('showModal'));
          showModal.show();
        });
    });
  });

  // 如果按钮是动态生成的,建议用事件委托写法替换上面的按钮绑定逻辑,避免重复绑定
  /*
  document.body.addEventListener('click', function(e) {
    if (e.target.matches('.exercice-class')) {
      e.preventDefault();
      const id = e.target.dataset.id;
      // 后续逻辑和上面一致
    }
  });
  */
});

相关问题解答

1. 如何使用变量作为参数打开Bootstrap Modal窗口

Bootstrap 5及以上版本原生支持JS调用,无需依赖jQuery,变量可以通过元素data属性传递,也可以直接传入模态框配置:

// 示例:将自定义参数存在触发按钮的data属性中,比如data-custom-param="xxx"
document.querySelectorAll('.exercice-class').forEach(button => {
  button.addEventListener('click', function() {
    // 取按钮上的自定义变量
    const customParam = this.dataset.customParam;
    const modalEl = document.getElementById('showModal');
    // 把变量存在模态框元素上,后续任意位置都可以读取
    modalEl.dataset.passedParam = customParam;
    
    // 初始化并打开模态框,支持传入自定义配置项
    const modal = new bootstrap.Modal(modalEl, {
      backdrop: 'static', // 配置项支持变量赋值
      keyboard: false
    });
    modal.show();
  });
});

后续需要使用传入的变量时,直接读取document.getElementById('showModal').dataset.passedParam即可。

2. 模态窗口内表单提交异步请求实现方案

用原生fetch即可实现和$.ajax高度对齐的逻辑,具体实现如下:

// 用事件委托监听表单提交,适配动态加载的表单
document.body.addEventListener('submit', function(e) {
  // 替换为你模态框内表单的选择器
  if (e.target.matches('#modalForm')) {
    e.preventDefault();
    // 序列化表单数据,等效jQuery的$(this).serialize()
    const formData = new FormData(e.target);
    
    // 发送异步请求,等效$.post
    fetch('你的后端提交接口地址', {
      method: 'POST',
      body: formData,
      headers: {
        'X-Requested-With': 'XMLHttpRequest' // 标记为AJAX请求,Symfony端可以用$request->isXmlHttpRequest()直接识别
      }
      // 如果需要提交JSON格式数据,替换为以下配置:
      /*
      headers: {
        'Content-Type': 'application/json',
        'X-Requested-With': 'XMLHttpRequest'
      },
      body: JSON.stringify(Object.fromEntries(formData))
      */
    })
    .then(response => response.json()) // 接口返回JSON用这个,返回HTML则用.text()
    .then(result => {
      // 请求成功处理逻辑:关闭模态框、提示成功、刷新列表等
      const modal = bootstrap.Modal.getInstance(document.getElementById('showModal'));
      modal.hide();
    })
    .catch(error => {
      // 请求失败处理逻辑
      console.error('提交失败:', error);
    });
  }
});

提示:Symfony端接收POST请求时记得校验CSRF令牌,表单内正常渲染{{ csrf_token('你的令牌标识') }}即可,FormData会自动携带该参数。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 08:48:03