0

使用 rails cast http://railscasts.com/episodes/324-passing-data-to-javascript?autoplay=true

将变量从我的控制器传递给 javascript。

我有一个按钮,当我点击它时,我希望它显示赞成票的数量。

我用gon。

但是,当我尝试运行它时,我的警报说即使我在控制器中设置了变量也没有定义

_source.html.erb

  <div class="panel-body">
  <%= include_gon(:init => true) %>
    <%=source.source %>
    <% @count = pluralize(source.upvotes.count,"upvote") %>
    <div id="count"><%= @count %></div>
    <%= button_to '+1', upvote_source_path(source), method: :post,remote: true %>

    <p><%= link_to "delete", [source.fact, source], method: :delete, data:{confirm: "are you sure?"} %></p>
  </div>

应用程序.html.erb

<!DOCTYPE html>
<html>
  <head>
    <title>Sourcemonkey</title>
    <%= include_gon(:init => true) %>
    <%= csrf_meta_tags %>

    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
  </head>

  <body>
    <%= yield %>
  </body>
</html>

sources_controller.rb -> 赞成行动

def upvote
        @source = Source.find(params[:id])
        @source.upvotes.create
        gon.count = @source.upvotes.count
        respond_to do |format|
        format.js {render :js =>"upDateCount()"}
        format.html { redirect_to :none}
        end
    end

upvote.js.erb

function upDateCount(){
    alert(gon.count)
 }

路线.rb

Rails.application.routes.draw do
  # mount Ckeditor::Engine => '/ckeditor'
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
  root to: "facts#index"

  resources :facts do
    resources :sources
  end

  resources :sources do
    member do
        post 'upvote'
    end
  end

  resources :upvote
end

欣赏想法,谢谢

4

1 回答 1

1

在这种情况下,可能更容易将投票计数传递给upDateCount

format.js {render :js =>"upDateCount(#{@source.upvotes.count})"}

并在那里使用参数而不是gon数据。

于 2016-09-09T08:17:43.860 回答