开发者

How to pass JavaScript variable to Rails instance variables?

Here is the jav开发者_如何学运维ascript 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.


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


you can try client_variable gem, it wrap some functions for you to do it easier

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜