Rails 4如何捕获ajax:成功事件

我在Rails 4.0上。

我正在发送这样的事件(注意:remote => true):

true, :class=>"rate-btn yes-btn btn btn-default btn-sm"} %> 

我的控制器看起来像这样:

  def rate video = Video.find_by( hashed_id: params[:id]) action = params[:yesno] puts video.hashed_id puts action respond_to do |format| if (action=='yes') new_rating = video.rating==1 ? 0 : 1 video.update( is_new:0, rating: new_rating ) format.html { redirect_to controller:'projects', action: show, id: video.project.hashed_id } format.json { head :no_content } format.js { render :nothing=>true } end if (action=='no') new_rating = video.rating==-1 ? 0 : -1 video.update( is_new:0, rating: new_rating ) format.html { redirect_to controller:'projects', action: show, id: video.project.hashed_id } format.json { head :no_content } format.js { render :nothing=>true } end end end 

我有点使用format.json / format.html,因为我不完全理解应该从AJAX请求应用哪一个。

在视图上(按钮所在的位置)我有这个:

 $(document).ready( function($) { console.log('ready'); $(document).ajaxSuccess( function(data) {alert(data);} ) $(document).ajaxError( function(data) {alert(data);} ) $('.rate-btn').closest('form').on('ajax:success', function() { console.log('ajax:success!'); }); $('.button_to').bind("ajax:success", function() { console.log( 'test' ); }); }); 

单击按钮后,我在控制台中ready ,但无论我做什么,我都无法在控制台中显示test 。 我错过了什么?

更新:

我在观看/log/development.log时尝试点击按钮,这就是我所看到的:

 Started POST "/videos/rate/lq7lv3218c/yes" for 127.0.0.1 at 2013-08-29 17:14:59 -0400 Processing by VideosController#rate as JS Parameters: {"authenticity_token"=>"es4wPqFrxxxxxFsbHQR/gAzofDC+ZwYsiiJ7RAQZUHk=", "id"=>"lq7lv3218c", "yesno"=>"yes"} [1m[36mVideo Load (0.3ms)[0m [1mSELECT `videos`.* FROM `videos` WHERE `videos`.`hashed_id` = 'lq7lv3218c' LIMIT 1[0m [1m[35m (0.1ms)[0m BEGIN [1m[36mSQL (0.3ms)[0m [1mUPDATE `videos` SET `rating` = 0, `updated_at` = '2013-08-29 21:14:59' WHERE `videos`.`id` = 18[0m [1m[35m (0.3ms)[0m COMMIT Rendered videos/rate.html.erb (0.0ms) Completed 200 OK in 7ms (Views: 2.0ms | ActiveRecord: 1.1ms) 

我是一个轨道n00b,但它看起来不错。

button_to帮助程序围绕提交按钮构建表单。 表单是接收data-remote属性的内容(请参阅: http : //apidock.com/rails/ActionView/Helpers/UrlHelper/button_to )。 所以,我试试这个:

 $('.rate-btn').closest('form').on('ajax:success', function() { console.log('ajax:success!') }); 

因为你在Rails 4.0上,我猜你是在使用jQuery 1.9。 对事件的约束似乎在那里发生了一些变化。 如果这对你有用,那么这可能是它的一部分。 从1.7开始,使用.on()进行事件绑定比.bind().on()

这就是为我解决问题的原因:

  1. 我在布局中加载我自己的jQuery(像这样: <%= javascript_include_tag "jquery-1.10.2.min", "data-turbolinks-track" => true %>它没有抛出任何错误,但显然是Rails还加载了自己的jQuery,它们在某种程度上相互冲突,因为当我删除了我的时候,所有jQuery仍然有效,我立即能够在视图中触发AJAX错误事件。但我仍然得到ajax错误……

  2. 我总是有一个/views/videos/rate.html.erb文件,因为我不确定它是否有必要(在CakePHP中它是)但是我没有任何东西。 这是空白的。 我不知道为什么,但是当我在该视图文件中添加1时,我突然开始触发ajax:成功事件。

我不明白为什么这解决了我的问题,所以如果有人能解释它我会更好地理解。

通过捕获ajax:completed来检查是否出现解析错误(或类似错误)。 检查那里的status参数。 您还可以在jquery_ujs.js设置断点。