Rails ajax:成功回调不会在生产中触发
我的ajax回调没有在我的生产环境中触发。 但是,它们在开发过程中没有错误。 为了讨论起见,我会简化一些事情。
假设我有一个使用remote: true
的链接remote: true
:
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:当我点击生产中的链接时会触发错误。
$(document).on("ajax:error", "#new-foo", function() { console.log("error"); });
我的生产日志没有显示任何错误,Chrome开发者工具中的网络选项卡显示200 OK
响应,部分为正文。
但是,Content-Type标题是生产中的text/javascript
,但正在开发中的text/html
。 为什么在生产中使用text/javascript
响应相同的代码?
问题是浏览器试图将响应主体作为JavaScript执行,因为发送回的Content-Type标头是text/javascript
而不是text/html
。
有很多方法可以解决这个问题。 我选择使用jQuery的$.ajax
函数来设置我所有 ajax调用的dataType
。 这将要求服务器发回text/html
。
$.ajaxSetup dataType: 'html'
但是,还有其他几种方法可以向服务器请求特定响应。 有关详细信息, 请参阅此StackOverflow答案 。
不过,仍有一个挥之不去的问题。 为什么相同的代码在开发中发送text/html
但在生产中发送text/javascript
?
如果谷歌把你带到这里(就像它对我做的那样)因为ajax:success
在一个稍微不同的情况下, 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
永远不会被调用的原因。
要解决此问题, form_class
在ERB中将class
更改为form_class
:
<%= button_to "Add Foo", new_foo_path, remote: true, form_class: 'new-foo' %>