gpt4 book ai didi

javascript - rails 4 中的 Ajax 请求更新值

转载 作者:行者123 更新时间:2023-11-30 17:36:39 24 4
gpt4 key购买 nike

我有一个投票按钮,它只显示投票数量,点击它,自动添加投票。现在我想添加一个 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 %>

Controller :

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);
}
});
})
})

关于javascript - rails 4 中的 Ajax 请求更新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21916426/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com