我有一个投票按钮,它仅显示投票的数量,单击该按钮会自动添加一个投票。现在,我想添加一个Ajax请求,以使页面不会刷新。不幸的是,我以前从未使用过Ajax,因此不知道如何在Rails中使用它。我尝试了一些教程,但似乎无济于事。
视图:
<%= link_to vote_path(:the_id => Amplify.all.where(question_id: question.id)[0].id, :the_user_id => @current_user.id), :remote => true do %>
<button class="fn-col-2 fn-col-m-3 amplify">
<%= image_tag "logo-icon-white.png" %>
<p class="count"><%= Amplify.all.where(question_id: question.id)[0].users.count %></p>
</button>
<% end %>
控制器:
def vote
@amplify = Amplify.find(params[:the_id])
@current_user = User.find(params[:the_user_id])
if @amplify.users.where(:id => @current_user.id).count != 0
@amplify.users.delete(@amplify.users.where(:id => @current_user.id).first)
else
@amplify.users << @current_user
end
@question = Question.where(id: @amplify.question_id)[0]
@amplify.update(:votes => @amplify.users.count)
@question.update_attributes(:votes => @amplify.votes)
redirect_to root_path
end
路线:
get '/vote' => "amplifies#vote", :as => "vote"
jQuery(document).ready(function($){
$('.amplify').on('click', function(){
var that = $(this);
$.ajax({
url: '/vote',
data: {id: 'your id'},
/**
* Response from your controller
*/
success: function(response) {
that.siblings('.count').first().text(response);
}
});
})
})
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句