how to access javascript variable in rails view

前端 未结 4 708
庸人自扰
庸人自扰 2020-12-21 08:55

Is there any way to access javasript variable inside the rails view. I just set some value of javascript variable and want to access it in rails view.

Thanks

相关标签:
4条回答
  • 2020-12-21 09:26

    You can pass a javascript variable to rails using AJAX. 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:

    <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. You can access it using 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.

    0 讨论(0)
  • 2020-12-21 09:28

    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.

    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>
    
    0 讨论(0)
  • 2020-12-21 09:38

    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.

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

    0 讨论(0)
  • 2020-12-21 09:42

    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>
    
    0 讨论(0)
提交回复
热议问题