How to pass a javascript variable into a erb code in a js view?

前端 未结 8 1951
时光取名叫无心
时光取名叫无心 2020-11-27 06:19

I have this Javascript view in my Rails 3 project:

app/views/expenses/new_daily.js.erb

var i = parseInt($(\'#daily\').attr(\'data-num\')) + 1;
//$(\'         


        
相关标签:
8条回答
  • 2020-11-27 06:35

    Check out the gon gem. https://github.com/gazay/gon

    It gives you a simple object you can pass variables to that will be available to your scripts via window.gon

    Also referenced here http://railscasts.com/episodes/324-passing-data-to-javascript

    0 讨论(0)
  • 2020-11-27 06:36

    As far as i know there is no way to do it directly and the reason is fairly simple too, html is executed at the server side and javascript is a client side language which means its executed in your local browser, thats why if you even try to pass a variable between the two you'll have to make a request to the server, However this problem is tackled by calling an AJAX request, this AJAX request does the same thing as sending a new request to the server however it does that without refreshing or reloading the page to it gives the users the illusion that no request was made.

    a guy asks a similar question Here

    and you can learn more about AJAX Here on MDN:

    0 讨论(0)
  • 2020-11-27 06:38

    Here's a few different options on how to do it:

    http://jing.io/t/pass-javascript-variables-to-rails-controller.html

    0 讨论(0)
  • 2020-11-27 06:42

    The best other answers here are right that this can't be done by passing the javascript variable into an erb partial, since it is rendered on the server, not the client.

    But since anyone looking for this is probably interested in a work-around solution, which I don't see here, I will post this example that works well with Rails UJS and Turbolinks.

    First, you set up your controller to return a partial as HTML:

    format.html { render partial: "new_expense" }
    

    Next, write a javascript AJAX function in app/views/expenses/new_daily.js.erb:

    var i = parseInt($('#daily').attr('data-num')) + 1;
    
    $.ajax({
      url: '/daily',
      type: 'GET',
      dataType: 'html',
      contentType: "application/html",
      success: function(response) { 
    
          $('#daily').replaceWith(response)
    
          $('#daily').attr('data-num', i);
      }
    });
    

    This is going to get your Rails partial as an html fragment that you can use to replace that part of your rendered page. You can use jQuery to get your data-num attribute value, do some math on it, replace the partial in your view, and then set the attribute value again.

    You may ask why go to all the trouble of getting the Rails partial and replace it on the page, instead of just getting the data attribute, doing math on it, and setting that? The answer is that this is the best, and perhaps the only way of doing something which is really essential when rendering a Rails partial using UJS while handling an asynchronous response to an action.

    If you are handling an asynchronous response from your server in a create.js.erb template, then your variables (@daily, for example) are not going to reflect the work done after the request has completed (for example, if there has been processing on a background server like Sidekiq). In that case you don't have up-to-date action response variables to pass into your Rails partial in the js.erb file, but you also can't pass the javascript data response into your partial, as pointed out in this question.

    As far as I know, this approach is the only way to get a fully up-to-date partial after receiving a response to an asynchronous response (not shown). This get you the up-to-date partial, allows you to get your javascript into it, and is flexible enough to work in pretty much any use case.

    0 讨论(0)
  • 2020-11-27 06:43

    1) You may create a js tag with global variable in you erb template, after that you will be able to access that variable from any js file

    <%= javascript_tag do %>
       window.productsURL = '<%= j products_url %>';
    <% end %>
    

    2) You can pass data to data-attribute in erb template and access it by js on client side that way $('#products').data('products')

    <%= content_tag "div", id: "products", data: {products: Product.limit(10)} do %>
       Loading products...
    <% end %>
    

    3) You can use gon, to use your Rails variables in your js

    There is a good article, read it and fine solution for your specific case http://railscasts.com/episodes/324-passing-data-to-javascript, more comments are here http://railscasts.com/episodes/324-passing-data-to-javascript?view=asciicast

    0 讨论(0)
  • 2020-11-27 06:49

    Simple answer is you can't. Partials are expanded at server side, and JavaScript variables are set later at client side. You could make i (as a variable name) a parameter of the partial and use it there.

    render :partial => 'xx', :locals => { :variable => 'i' }
    

    And in partial

    alert(<%= variable %>);
    
    0 讨论(0)
提交回复
热议问题