【问题标题】:GON - not getting value in js.erb + Rails 5GON - 没有在 js.erb + Rails 5 中获得价值
【发布时间】:2017-03-24 03:33:39
【问题描述】:

宝石文件

gem 'gon'

这是我的 application.html.erb 文件。

<html>
  <head>
    <title>Test Title</title>
    <%= Gon::Base.render_data %>
    <%= 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>
    ....
  </body>
</html>

现在,在许多页面(索引)上,我使用 ajax 删除了我的记录。喜欢

<%= link_to "<i class='fa fa-times-circle-o'></i>".html_safe, section_path(sec_content, type: params[:type]), class: 'pull-right', title: 'Delete Section', data: {disable_with: "<i class='fa fa-spinner'></i>".html_safe, confirm: 'Are you sure want to delete ?'}, method: :delete, remote: true %>

在 Controller 中,销毁动作代码。

def destroy
  gon.test_id = 1
  section.destroy if section.present?      
end

现在,是去destroy.js.erb文件

console.log(gon)
alert(gon.test_id)
$("#section_<%= params[:id] %>").remove();

现在,console.log 没有什么可显示的,并且会出现警报,但它显示我“未定义”

谁能帮我在上面的代码中有什么问题,以便我可以在 js.erb 文件中使用 gon 吗?

提前致谢

【问题讨论】:

  • 我遇到了与 gon 相同的问题,我所做的是我在会话变量中分配值,例如 session[:test] = 1,然后将会话分配给 gon gon.test_id = session[:test],它工作正常
  • 你试过console.log(&lt;%= gon %&gt;) 吗?
  • @Зелёный - 出现错误 - ActionView::Template::Error (#:0xb13598f8> 的未定义局部变量或方法 `gon'):
  • 这个问题解决了吗?我遇到了同样的问题

标签: jquery ruby-on-rails ruby ruby-on-rails-5 gon


【解决方案1】:

在控制器中标记require 'gon' 并尝试。

【讨论】:

  • 仍然出现同样的错误。 console.log 没有什么可显示的,警报会出现,但它显示我“未定义”
【解决方案2】:

Afaik 你必须使用 gon watch 才能将 Gon 与 Ajax 一起使用。


你也应该这样做

<%= Gon::Base.render_data(init: true) %>

# instead of 
# <%= Gon::Base.render_data %>
# <%= include_gon(:init => true) %>

【讨论】:

  • 如果我按照 gon.watch 的说明进行操作,一切正常。你能告诉我你是如何实现 gon.watch 的吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-20
  • 2021-03-28
  • 2016-01-30
  • 2018-04-08
  • 2018-04-09
  • 2012-06-24
  • 1970-01-01
相关资源
最近更新 更多