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

Rails模态框表单提交后ajax:success参数未定义求助

Rails Ajax模态框表单提交:ajax:success参数为null的问题解决

你遇到的这个情况其实是Rails UJS版本差异导致的,我之前做项目的时候也踩过这个坑!

问题原因

在旧版的jquery-ujs(Rails 5及更早版本常用)中,ajax:success事件触发时,会直接把data、status、xhr作为回调函数的参数传递给你。但从Rails 6开始,官方把UJS重构为@rails/ujs,并且调整了事件参数的传递方式——现在这些数据都被放在了event.detail数组里,不再直接作为回调参数传入。这就导致你原来写的回调里,xhr、data、status这三个参数自然就成了null,而你找到的event.originalEvent.detail[2].response正是新版本里存放响应数据的地方。

解决方案

只需要调整回调函数里获取数据的方式,从event.detail中解构出需要的参数即可,修改后的代码如下:

(function() {
  $(function() {
    var modal_holder_selector, modal_selector;
    modal_holder_selector = '#modal-holder';
    modal_selector = '.modal';

    $(document).on('click', 'a[data-modal]', function(event) {
      var location;
      event.preventDefault();
      location = $(this).attr('href');
      $.get(location, function(data) {
        return $(modal_holder_selector).html(data).find(modal_selector).modal();
      });
      return false;
    });

    return $(document).on('ajax:success', 'form[data-modal]', function(event) {
      event.preventDefault();
      // 从event.detail中解构出正确的参数
      const [data, status, xhr] = event.detail;
      var url = xhr.getResponseHeader('Location');
      if (url) {
        window.location = url;
      } else {
        $('.modal-backdrop').remove();
        $(modal_holder_selector).html(data).find(modal_selector).modal();
      }
      return false;
    });
  });
}).call(this);

这样修改后,你就能正常拿到xhr、data和status参数,继续完成模态框的更新逻辑了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:07:38