【发布时间】:2015-12-22 23:15:32
【问题描述】:
我目前正在处理我的第一个 RoR 项目。现在我想将一个喜欢/不喜欢的系统集成到我的应用程序中。我有一些代码,但它仅在重新加载页面时才有效。我的目标是在不重新加载页面(使用 Ajax,而不是内置的)的情况下实现喜欢/不喜欢帖子的能力。那么,这是我的代码,这里有什么问题?
我的控制器
def like
@post=Post.find(params[:id])
@post.increment!(:like)
render :nothing => true, :status => 200
end
def dislike
@post=Post.find(params[:id])
@post.increment!(:dislike)
render :nothing => true, :status => 200
end
我的看法
<table>
<% if @post.count!=0 %>
<% @post.each do |p| %>
<%if !p.text.nil?%>
<tr data-post_id="<%= p.id %>">
<td><b class="margin"><h4><%=p.text%></b></h4></td>
<td>by <%= link_to p.user.username, profile_dashboard_path(p.user) %> </td>
<td><span class="glyphicon glyphicon-thumbs-up likeAction"><%= p.like %> </td>
<td><span class="glyphicon glyphicon-thumbs-down dislikeAction"><%= p.dislike %> </td>
<%end%>
<% end %>
<%else%>
There's no posts yet, but you can add <%=link_to "one", create_a_post_dashboard_path(current_user)%>
<%end%>
</table>
我的 js 文件,它位于 app/assets/javascripts/dashboard.js,所以我没有任何名称为 like.js.erb 或 dislike.js.erb 的 js 文件(我不确定我是否需要他们)
jQuery(function($) {
$(".likeAction").click(function(){
var current_post_tr = $(this).parents('tr')[0];
$.ajax({
url: 'http://localhost:3000/dashboard/' + $(current_post_tr).attr('data-post_id') +'/like',
type: 'PUT',
success: function(){
$(".likeAction").hide().fadeIn();
location.reload();
}
});
});
$(".dislikeAction").click(function(){
var current_post_tr = $(this).parents('tr')[0];
$.ajax({
url: 'http://localhost:3000/dashboard/' + $(current_post_tr).attr('data-post_id') +'/dislike',
type: 'PUT',
success: function(){
$(".dislikeAction").hide().fadeIn();
location.reload();
}
});
});
});
【问题讨论】:
-
您在 ajax 成功后重新加载页面。您是否尝试过在成功后通过减/加 1 来更改 $('.dislikeAction') 或 $('.likeAction') 的文本?
-
不,因为我在 jQuery 方面不太强。你能给我举个例子吗?
-
var dislikes = $(".dislikeAction").text();$(".dislikeAction").text(parseInt(dislikes)+1) -
如果你的意思是这样的 jQuery(function($) { $(".likeAction").click(function(){ var likes = $(".likeAction").text(); $.ajax({ $(".likeAction").text(parseInt(likes)+1); }); }); });然后就不行了
-
不,我不是那个意思。当您的 ajax 帖子成功时,尝试增加“喜欢”和“不喜欢”。
success: function(){$(".dislikeAction").hide().fadeIn();var dislikes = $(".dislikeAction").text();$(".dislikeAction").text(parseInt(dislikes)+1) // similarly for likes}
标签: ruby-on-rails ajax ruby-on-rails-3 ruby-on-rails-4