简体   繁体   中英

How to pass JavaScript variable to Rails instance variables?

Here is the javascript in the .js.erb

$(document).ready(function () {
         var i = 888
      $( "#previewpicture" ).html( "<%= escape_javascript( render( :partial => "show_picture", :locals => { :@v_url => 'i'  }   ) ) %>" );
     });

@v_url is defined in the controller and alert(<%= @v_url %>) is in the partial _show_picture.html.erb

The alert display i instead of 888. What is the correct syntax for :locals => { :@v_url => 'i'}

Thanks Clin

You cannot do this, as JavaScript is a client-side language and Ruby is a server-side language. Ruby is parsed not only before JavaScript, but also on a completely separate machine with no way of interacting between the two.

Work out an alternative solution to your problem.

As Ryan Bigg pointed, you cannot do this. But if you need a certain value to exist in both the server-side where your Rails is and client-side where your JS is, you would probably be better off storing that value in the server-side.

For example, you can have in your Rails controller:

@i = 888

And in your js template:

var i = #{@i};

Technically, this is passing a variable from Rails instance variable to JS variable. The reverse.

If you want to pass a JS variable from the client to the server, you can call an ajax request to the server passing in the variable as a parameter, and then let Rails respond with the template to be updated on your page.

This won't work since JS is executed after the page is shown on your browser. However, if you need something on the page that depends on a Javascript condition or variable, you should make an AJAX call to your server, get the markup and place it in your page.

您可以尝试client_variable gem ,它包装了一些功能,使您更轻松

I like the jQuery native data cross-browse key-value storage to save server-side variable depends on a certain object. JS variables are fine, but if you need to use object-oriented variables, just try that approach:

# erb file
<% javascript_tag do %>
  var i    = <%= server_variable %> // 888
  var obj  = $('#previewpicture');
  var data = $.data(obj, "vars", {v_url: i})
<% end %>

<%= render :partial => "show_picture" %> #v_url will be assign by JS on page load


# js file
$(document).ready(function () {
  $('#previewpicture').attr('v_url', data['v_url'])
})

It is possible to mingle the two with erb. For example, with backbone.js:

#something.html.erb 
<script>
    function makeSomething() {
        Something.create({
            prop1: val1,
            prop2: val2,
            prop3: val3
          });
    }
</script>

Then in your controller:

def create
   ...some logic
  render :json => something
end

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