gpt4 book ai didi

javascript - 将变量传递给 JavaScript Rails

转载 作者:行者123 更新时间:2023-12-03 06:09:08 24 4
gpt4 key购买 nike

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

将变量从我的 Controller 传递到 JavaScript。

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

我正在使用 gon。

当我尝试运行它时,我的警报说即使我在 Controller 中设置了该变量也未定义

_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>

application.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

感谢您的想法,谢谢

最佳答案

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

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

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

关于javascript - 将变量传递给 JavaScript Rails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39405390/

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