简体   繁体   English

Ruby on Rails:如何将值传递给 javascript

[英]Ruby on Rails : how to pass value to javascript

I want to pass the value from <%= controller.controller_name %> <%= controller.action_name %> to javascript as below我想将值从<%= controller.controller_name %> <%= controller.action_name %>传递给 javascript 如下

return (document.body.className += " load-done 
            '<%= controller.controller_name %>' '<%= controller.action_name %>'
        ");

but it doesn't work, can anyone advise on this?但它不起作用,任何人都可以就此提出建议吗?

The question is lacking information so I just guess you want to pass some data directly from the controller to your JS code.这个问题缺少信息,所以我猜您想将一些数据直接从 controller 传递给您的 JS 代码。 There are two "normal" ways to do this.有两种“正常”方法可以做到这一点。 The first is to do a direct call to the controller as a http call and return the response as a json. The second method is to pass the data as a class variable, then you can access it in the views folder from the html files.第一种是直接调用 controller 作为 http 调用并返回响应作为 json。第二种方法是将数据作为 class 变量传递,然后您可以从 html 文件的视图文件夹中访问它。 Here you can pass the variable to a div, span or whatever and access it in the JS by finding the html tag in the JS like so:在这里,您可以将变量传递给 div、span 或其他任何东西,并通过在 JS 中找到 html 标记来在 JS 中访问它,如下所示:

# controllers: 

def some_controller_method
  @temp = 'example data, could be any type'
end

# views
<%= content_tag :div, class: "some_class", data: {temp: @temp} do %>
<% end %>

# JS
$('.some_class').data('temp')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM