【问题标题】:Rails ajax:success callback not triggering in productionRails ajax:成功回调未在生产中触发
【发布时间】:2013-04-15 02:26:36
【问题描述】:

我的 ajax 回调没有在我的生产环境中触发。但是,它们在没有错误的情况下在开发中触发。为了讨论,我会简化一些事情。

假设我有一个使用remote: true的链接:

<%= link_to "Add Foo", new_foo_path, remote: true, id: 'new-foo' %>

foos_controller.rb

class FoosController < ApplicationController
  def new
    @foo = Foo.new
    render partial: 'form' if request.xhr?
  end
end

使用 Chrome 的控制台,我绑定到ajax:success

$(document).on("ajax:success", "#new-foo", function() { console.log("success!"); });

在开发中这工作正常;我得到了“成功!” Chrome 控制台中的消息。

但是,在生产中,它没有。正在发出请求,响应为 form 部分,但回调未触发。

有什么想法吗?

PS。以下也不起作用

$("#new-foo").bind("ajax:success", function() { console.log("success!"); })

config/environments/production.rb 没有变化。

编辑:事实证明,当我在生产环境中单击链接时,会触发 ajax:error。

$(document).on("ajax:error", "#new-foo", function() { console.log("error"); });

我的生产日志没有显示任何错误,Chrome 开发者工具中的网络标签显示 200 OK 响应,其中部分为正文。

但是,Content-Type 标头在生产中是 text/javascript,而在开发中是 text/html 为什么相同的代码在生产中响应 text/javascript

【问题讨论】:

    标签: ruby-on-rails ajax


    【解决方案1】:

    问题在于浏览器试图将响应正文作为 JavaScript 执行,因为返回的 Content-Type 标头是 text/javascript 而不是 text/html

    有多种方法可以解决此问题。我选择使用 jQuery 的 $.ajax 函数来设置 all 我的 ajax 调用的 dataType。这将要求服务器发回text/html

    $.ajaxSetup
      dataType: 'html'
    

    但是,还有其他几种方法可以向服务器请求特定响应。 See this StackOverflow answer了解详情。

    但仍有一个挥之不去的问题。为什么相同的代码在开发中发回 text/html 而在生产中发回 text/javascript

    【讨论】:

      【解决方案2】:

      如果 Google 将您带到这里(就像它对我所做的那样),因为 ajax:success 在稍微不同的情况下不适合您 - 当您使用 button_to 而不是 link_to 时,这可能会为您节省一些头撞。

      假设你有这个修改后的 ERB:

      <%= button_to "Add Foo", new_foo_path, remote: true, class: 'new-foo' %>
      

      这个 JS 不行:

      $(document).on("ajax:success", ".new-foo", function() { console.log("success!"); });
      

      这将不起作用,因为类 new-foo 呈现在 input 标记上,而 data-remote="true" 呈现在 form 标记上。 ajax:success 事件在 form 标签上触发 - 而不是子 input 标签,这就是 console.log 永远不会被调用的原因。

      要解决此问题,请将 ERB 中的 class 更改为 form_class

      <%= button_to "Add Foo", new_foo_path, remote: true, form_class: 'new-foo' %>
      

      【讨论】:

        猜你喜欢
        • 2013-09-14
        • 2012-05-04
        • 2013-03-20
        • 1970-01-01
        • 1970-01-01
        • 2014-01-12
        • 2014-02-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多