简体   繁体   English

如何在rails视图中访问javascript变量

[英]how to access javascript variable in rails view

Is there any way to access javasript variable inside the rails view. 有没有办法在rails视图中访问javasript变量。 I just set some value of javascript variable and want to access it in rails view. 我只是设置了javascript变量的一些值,并希望在rails视图中访问它。

Thanks 谢谢

You have to understand that ruby code in your views gets executed on the server - before any javascript on the page gets a change to be executed. 您必须了解视图中的ruby代码在服务器上执行 - 在页面上的任何javascript获得执行更改之前。

That's why you cannot do stuff like this: 这就是为什么你不能做这样的事情:

<script>
  var js_var = 1;
</script>

<%= get_value_of_js_var_somehow %>

The other way round it works: 另一种方式是:

<script>
  var js_var = <% generate_value_with_ruby %>;
  do_something_in_javascript_with_js_var();
</script>

You can pass a javascript variable to rails using AJAX. 您可以使用AJAX将javascript变量传递给rails。 For example if you want to pass the id for an user to a method in a rails controller from javascript you can execute the following code: 例如,如果要将用户的id从javascript传递给rails控制器中的方法,则可以执行以下代码:

<script>
  var id = 1;
  <%= remote_function :url => {:controller=>'controller_name', :action=>'method_name'}, :with => "'user_id=' + id" %>
</script>

You will receive the variable through a POST request, as a parameter. 您将通过POST请求接收变量作为参数。 You can access it using params[:user_id] . 您可以使用params[:user_id]访问它。

def method_name
  if params[:user_id].exists?
    u = User.where('id = ?', params[:user_id]).first
  end
  puts u.path
end

Hope I've answered your question. 希望我已经回答了你的问题。

If you have this Javascript variable in a higher piece of javascript (per se: the application.js), then you can always just reference it in the view. 如果你在更高的javascript(本身:application.js)中有这个Javascript变量,那么你总是可以在视图中引用它。

#application.js
var someVar = "Hello World";

Then in your view (executed on the client), you could to... 然后在你的视图中(在客户端执行),你可以......

<script type='text/javascript'>
  alert(someVar);
</script>

I think we need more specific ellaboration if one of these three posts doesn't answer your question. 如果这三个帖子中的一个没有回答你的问题,我认为我们需要更具体的阐述。

Suppose we are having script as follows 假设我们有如下脚本

<script type="text/javascript">
  var a="some value";
  document.getElementById('tagid').innerHTML='<%= tag(:div,content_tag(:p,' " +a+ " '), :id=>' " +a+ " ', name=>"somename") %>';
</script>

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

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