Rails Ajax:成功回调未在生产中触发 [英] Rails ajax:success callback not triggering in production
问题描述
我的ajax回调未在生产环境中触发.但是,它们在开发过程中没有出现错误.为了讨论方便,我将简化一些事情.
My ajax callbacks are not triggering in my production environment. However, they are trigering in development with no errors. I'll simplify things for the sake of discussion.
假设我有一个使用 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
:
Using Chrome's console, I bind to ajax:success
:
$(document).on("ajax:success", "#new-foo", function() { console.log("success!"); });
在开发中,这很好用;我得到了成功!"Chrome控制台中显示错误消息.
In development this works fine; I get the "success!" message in the Chrome console.
但是,在生产中却没有.正在发出请求,响应为 form
部分,但不会触发回调.
In production, however, it does not. The request is being made, the response is the form
partial, but the callback does not fire.
有什么想法吗?
PS.以下也不起作用.
$("#new-foo").bind("ajax:success", function() { console.log("success!"); })
config/environments/production.rb
不变.
编辑:事实证明,当我单击生产环境中的链接时,就会触发ajax:错误.
EDIT: It turns out ajax:error is being triggered when I click the link in production.
$(document).on("ajax:error", "#new-foo", function() { console.log("error"); });
我的生产日志没有显示任何错误,并且Chrome开发人员工具中的网络"标签显示了 200 OK
响应,其中部分是正文.
My production logs don't show any errors, and the network tab in Chrome developer tools is showing a 200 OK
response with the partial as the body.
但是,Content-Type标头在生产中是 text/javascript
,而在开发中是 text/html
.为什么相同的代码会做出响应在生产中使用 text/javascript
?
推荐答案
问题是浏览器试图将响应主体作为JavaScript执行,因为发送回的Content-Type标头是 text/javascript
而不是 text/html
.
The problem was that the browser was trying to execute the response body as JavaScript since the Content-Type header being sent back was text/javascript
rather than text/html
.
有多种方法可以解决此问题.我选择使用jQuery的 $.ajax
函数来设置我的ajax调用的 all 的 dataType
.这将要求服务器发回 text/html
.
There are a number of ways to fix this. I chose to use jQuery's $.ajax
function to set the dataType
of all my ajax calls. This will ask the server to send back text/html
.
$.ajaxSetup
dataType: 'html'
但是,还有其他两种方法可以向服务器请求特定的响应.请参阅此StackOverflow答案详细信息.
However, there are a couple other ways to ask the server for a specific response. See this StackOverflow answer for details.
但是,仍然存在一个挥之不去的问题.为什么相同的代码在开发中会发回 text/html
而在生产中会发回 text/javascript
?
There is still a lingering question, though. Why was the same code sending back text/html
in development but text/javascript
in production?
这篇关于Rails Ajax:成功回调未在生产中触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!