在Rails上,我正在尝试创建无限按钮,使用户能够多次喜欢,但Ajax似乎无法正常工作。这是我的代码。
应用程序/视图/帖/ _like.html.erb
<%= link_to 'B', post_like_path({:id => @post}), :class => 'like', :method => :post, :remote => true %>
应用程序/控制器/ posts_controller.rb
def like
post = Post.find(params[:id])
post.like += 1
post.save
if request.xhr?
puts 'test' #'test' appears when like clicked
else
redirect_to :back
end
end
应用程序/资产/ JavaScript的/的application.js
$(document).on('ajax:success', function(e) {
console.log('test1') // 'test1' does not appear!!!
});
console.log('test2') // 'test2' does appear
答案 0 :(得分:0)
由于您要显示您的puts语句,您似乎并不太远,但您的路线需要响应您的ajax请求。为了做到这一点,我会在你喜欢的方法中设置一个respond_to块
def like
post = Post.find(params[:id])
post.like += 1
post.save
respond_to do |format|
format.js
end
end
有了这个,你就可以创建一个js模板app / views / posts / like.js.erb
#like.js.erb
console.log('like clicked');
答案 1 :(得分:-1)
我发现有几个问题,你使用path_helper你并没有将@post实例化为一个变量(至少不是你所显示的那个),你的ajax方法也应该可能看起来更接近这个...
#app/views/posts/_like.html.erb
<%= link_to 'B', post_like_path(:id => @post.id), :class => 'like', :method => :post, :remote => true %>
#config/routes.rb
get "/some-path", to: "posts#index"
post "/some-path", to: "posts#like", as: "post_like"
#app/controllers/posts_controller.rb
def index
@post = Post.find(params[:id])
end
def like
post = Post.find(params[:id])
post.like += 1
post.save
end
#app/assets/javascript/application.js
$(".like").click(function(event) {
event.preventDefault();
url = $(this).attr('href');
$.ajax({
type: 'POST',
url: url,
success: console.log('success')
});
});