【发布时间】:2015-12-18 20:02:53
【问题描述】:
我想在我的 RoR 应用程序上添加喜欢/不喜欢的能力。我怎样才能通过 Ajax 请求实现它?
不喜欢和喜欢 - 是整数我怎样才能发出 Ajax 请求,而不是我可以发送我想要在我的方法中增加“喜欢”或“不喜欢”计数器的数据
我有一张有帖子的桌子:
#app/views/dashboard/view.html.erb
<table>
<%if @post.count!=0%>
<%@post.each do |p|%>
<%if !p.text.nil?%>
<tr>
<td><b class="margin"><h4><%=p.text%></b></h4></td>
<td>by <%=p.user.username%> </td>
<td><span class="glyphicon glyphicon-thumbs-up likeAction"><%= link_to p.like, dashboard_like_path, :remote => true, :id => 'likecount' %> </td>
<td><span class="glyphicon glyphicon-thumbs-down"><%= link_to p.dislike, dashboard_dislike_path, :remote => true, :id => 'dislikecount' %> </td>
<%end%>
<% end %>
<%else%>
There's no posts yet, but you can add <%=link_to "one", dashboard_posts_create_a_post_path%>
<%end%>
</table>
我的 js 文件
#app/views/dashboard/view.js
$('#likecount').text(@post.like);
$('#dislikecount').text(@post.dislike);
我在控制器中的方法:
#app/controller/dahsboard_controller.rb
def like
@post.increment!(:like)
respond_to do |format|
format.html
format.js
end
end
def dislike
@post.increment!(:dislike)
respond_to do |format|
format.html
format.js
end
end
我在 assets/javascripts 中的dashboard.js
jQuery(function($) {
$("likeAction").click(function(){
$.ajax({
url: dashboard_like_path,
type: 'POST',
success: function(){
$('#linkcount').text(data);
}
error: function(error){
alert(error);
}
});
});
});
【问题讨论】:
标签: javascript jquery ruby-on-rails ajax ruby-on-rails-4