我试图通过使用ajax点击喜欢或不喜欢更新投票计数,以便页面不必重新加载。这些按钮似乎在服务器日志中工作,我在控制台日志中没有出现任何错误。
除非我刷新页面,否则投票计数不会更新。如何通过ajax / json更新投票计数?
使用按钮显示视图
<span class="up"><%= @lyric.get_upvotes.size %> </span>
<%= link_to like_lyric_path(@lyric), class: 'voteup', remote: true, data: { type: :json }, method: :get do %>
<span class="glyphicon glyphicon-chevron-up" aria-hidden="true"></span>
<% end %>
<span class="down"><%= @lyric.get_downvotes.size %></span>
<%= link_to dislike_lyric_path(@lyric), class: 'votedown', remote: true, data: { type: :json }, method: :get do %>
<span class="glyphicon glyphicon-chevron-down" aria-hidden="true"></span>
<% end %>
JS
$('.voteup')
.on('ajax:send', function () { $(this).addClass('loading'); })
.on('ajax:complete', function () { $(this).removeClass('loading'); })
.on('ajax:error', function () { $(this).after('<div class="error">There was an issue.</div>'); })
.on('ajax:success', function () {
$('.up').html('<%=escape_javascript @lyric.get_upvotes.size.to_s %>');
$('.down').html('<%=escape_javascript @lyric.get_downvotes.size.to_s %>');
});
</script>
<script>
$('.votedown')
.on('ajax:send', function () { $(this).addClass('loading'); })
.on('ajax:complete', function () { $(this).removeClass('loading'); })
.on('ajax:error', function () { $(this).after('<div class="error">There was an issue.</div>'); })
.on('ajax:success', function () {
$('.up').html('<%=escape_javascript @lyric.get_upvotes.size.to_s %>');
$('.down').html('<%=escape_javascript @lyric.get_downvotes.size.to_s %>');
});
</script>
控制器
def upvote
@lyric.upvote_by current_user
respond_to do |format|
format.html {redirect_to :back }
format.json { render json: { data: @lyric.get_upvotes.size} }
format.js { render :layout => false }
end
end
def downvote
@lyric.downvote_by current_user
respond_to do |format|
format.html {redirect_to :back }
format.json { render json: { data: @lyric.get_downvotes.size } }
format.js { render :layout => false }
end
end
答案 0 :(得分:1)
获取的JS加载一次页面将保持静态。所以行$('.up').html('<%=escape_javascript @lyric.get_upvotes.size.to_s %>');
和
需要在服务器上运行的$('.down').html('<%=escape_javascript @lyric.get_downvotes.size.to_s %>');
(因为它是在服务器上执行的rails代码)才能获得@lyric.get_upvotes.size.to_S
的更新值。相反,你可以做的是,
format.json
已经返回json
- {data: 10}
....其中10表示投票数(向上或向下)。
将ajax:success
和.voteup
类的.votedown
修改为此
$('.voteup').
on('ajax:success', function (result) {
$('.up').html(result.data + ' Upvotes');
});
$('.votedown').
on('ajax:success', function (result) {
$('.down').html(result.data + ' Downvotes');
});