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

基于DRY原则实现多模态框Ajax复用,避免代码重复

复用Ajax模态框代码的解决方案

问题描述

我正尝试通过Ajax请求处理多个模态框,同时避免重复编写Ajax代码。目前模态框功能正常运行,但希望无需重复编写jQuery代码,现寻求可行方案。

现有jQuery代码:

$(document).on("click", "#modal-btn", function () {
  $.ajax({
    type: "GET",
    url: "transfer_transactions/new",
    dataType: "script",
    success: (response) => {
      console.log(response);
      $("#modal-content").html(response);
    },
  });
});

transaction/index.html.haml代码:

= link_to 'New', new_transfer_transaction_path,  id:"modal-btn",  remote: true , :'data-target' => "#exampleModalStaticBackdrop", :'data-toggle' => "modal"
//index code...
#exampleModalStaticBackdrop.modal{"data-animations" => "fadeInDown, fadeOutUp", "data-static-backdrop" => ""}          
  .modal-dialog.max-w-2xl
    .modal-content
      .modal-header
        %button.close.la.la-times{"data-dismiss" => "modal", :type => "button"}
      .modal-body
        #modal-content

我希望在country/index.html.haml中使用该模态框,无需重复编写Ajax代码,请问是否有可行方法?


解决方案

1. 用类替代ID,通过data属性传递请求参数

ID是唯一标识,无法复用,换成类选择器绑定事件,同时用data-*属性存储每个按钮的请求地址、模态框目标等信息:

  • 修改jQuery代码:
// 绑定类选择器,从data属性获取动态参数
$(document).on("click", ".modal-trigger-btn", function () {
  const $btn = $(this);
  const targetUrl = $btn.data('url');
  const modalTarget = $btn.data('target');

  $.ajax({
    type: "GET",
    url: targetUrl,
    dataType: "script",
    success: (response) => {
      console.log(response);
      $("#modal-content").html(response);
    },
    error: (xhr) => {
      console.error('请求失败:', xhr);
      $("#modal-content").html('<p>加载失败,请重试</p>');
    }
  });
});
  • 修改transaction/index.html.haml的按钮:
= link_to 'New', '#', class:"modal-trigger-btn", data: { url: new_transfer_transaction_path, target: "#exampleModalStaticBackdrop", toggle: "modal" }
  • 在country/index.html.haml中添加按钮:
= link_to '新建国家', '#', class:"modal-trigger-btn", data: { url: new_country_path, target: "#exampleModalStaticBackdrop", toggle: "modal" }

这样不管是transaction还是country页面,只要给按钮加上.modal-trigger-btn类,并用data-url指定请求地址,就能复用同一段Ajax代码。

2. 全局复用模态框结构

把模态框的HTML结构(#exampleModalStaticBackdrop和#modal-content)放到应用的全局布局文件(比如layouts/application.html.haml)中,这样所有页面都能直接调用,不用在每个页面重复编写模态框代码。

3. 优化:手动控制模态框显示

如果使用Bootstrap模态框,可以去掉data-toggle属性,在Ajax请求完成后手动触发模态框显示,逻辑更可控:

  • 修改后的jQuery代码:
$(document).on("click", ".modal-trigger-btn", function () {
  const $btn = $(this);
  const targetUrl = $btn.data('url');
  const modalTarget = $btn.data('target');

  $.ajax({
    type: "GET",
    url: targetUrl,
    dataType: "script",
    success: (response) => {
      $("#modal-content").html(response);
      $(modalTarget).modal('show');
    },
    error: (xhr) => {
      console.error('请求失败:', xhr);
      $("#modal-content").html('<p>加载失败,请重试</p>');
      $(modalTarget).modal('show');
    }
  });
});
  • 对应的按钮代码:
= link_to 'New', '#', class:"modal-trigger-btn", data: { url: new_transfer_transaction_path, target: "#exampleModalStaticBackdrop" }

这种方式避免了Bootstrap默认data-toggle可能带来的逻辑冲突,让模态框的显示完全由Ajax请求结果控制。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 04:10:39