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

标签 javascript jquery ruby-on-rails ajax

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

相关文章:

javascript - 将附加 Prop 传递给 Div - React

javascript - 单击“注销”使 session 无效并关闭浏览器选项卡

javascript - 用户单击组合框后重新加载页面(有一些规则)

jquery - 使用 JQuery 的 Grails 项目,无需插件

javascript - $.index() 等同于第 n 个 child 吗?

ruby-on-rails - 加速 RSpec 请求规范的方法

ruby-on-rails - 在rename_column迁移期间生成的异常

javascript - 如何为对象设置标志而不影响AngularJS中的其他$scope值?

javascript - IE 7 中出现奇怪的 javascript 错误,但 IE 8 中没有

ruby-on-rails - 如何使用 sprockets 架构在 Rails 3.1 中引用 JQuery 插件中的文件?