我正在使用 Rails 4.0。
我正在发送这样的事件(注意:remote=>true):
<%= button_to 'yes', {controller:'videos', action:'rate', id: video.hashed_id, yesno:'yes'}, {:remote=>true, :class=>"rate-btn yes-btn btn btn-default btn-sm"} %>
我的 Controller 看起来像这样:
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 请求中应用哪一个。
在 View (按钮所在的位置)上我有这个:
$(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' );
});
});
单击按钮后,我在控制台中得到准备好
,但无论我做什么,我都无法让测试
显示在控制台中。我错过了什么?
更新:
我尝试在观看/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)
我是 Rails 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。事件的绑定(bind)似乎在那里发生了一些变化。因此,如果这以前对您有用,那么这可能是其中的一部分。自 1.7 以来,使用 .on()
进行事件绑定(bind)优于 .bind()
。
关于jquery - Rails 4 如何捕捉 ajax :success event,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18518990/