简体   繁体   中英

Passing javascript variable into erb tag

I've been looking into how to use a javascript variable within erb <% %> tags. This will have to be done via AJAX (see How to pass a javascript variable into a erb code in a js view? ). I'm quite new to JS and especially new to AJAX and finding an example of this in action would be awesome.

Consider the following simple scenario where all that is needed to be passed from the JS to the ERB is a simple bit of text:

HTML: <input id="example-input" type="text">

$(function() {
  $('input#example-input').keyup(function(e) {
    if(e.keyCode == 13){
      var input = $('input#example-input').val();
      <% puts input.upcase %>
    }
  }
});

Notice that the input will not be defined within the erb tags, and hence this will throw an error.

I believe you're assuming that the line <% puts input.upcase %> will execute ruby code after your javascript line var input = $('input#example-input').val(); . If that is what you were thinking, this is incorrect. In the example you've given:

  • The <% puts input.upcase %> gets executed when the page loads.
  • input in <% puts input.upcase %> is a ruby variable
  • input in var input = $('input#example-input').val(); is a javascript variable

If you had a variable that you set on the server side, you could say something like this in your javascript:

var my_js_var = '<%= a_str_in_ruby %>';

and that would work fine for intializing a variable on the javascript side.

However since you want to request data from the client side (aka javascript) to your server side (to be handled by rails controller), what you should be doing is submitting an ajax request. There's a section in the rails documentation that contains examples, and a good railscasts episode (if you're a paying member).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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