简体   繁体   中英

How to pass a variable from controller to javascript within a view?

I have an array @fields which has text and an id, asset_id. To pass local variables from controller to view in render we use

render(:template => "assets/invalid", :locals => {:asset_id => params[:id], :fields => @fields})

The view is

<div id="panel">
  <script>
    alert('Invalid values for ')
    window.location = "../assets/" 
  </script>
</div>

This should generate a popup box. However, I want the popup box to redirect to "../assets/asset_id" and also display 'Invalid values for + fields'

The following doesn't work,

<div id="panel">
  <script>
    var fields = fields
    var asset_id = asset_id 
    alert('Invalid values for ' + fields )
    window.location = "../assets/" + asset_id 
  </script>
</div>

Could it be as simple as this?

<div id="panel">
  <script>
    var fields = <%= fields.to_json %>
    var asset_id = <%= asset_id.to_json %>
    alert('Invalid values for ' + fields )
    window.location = "../assets/" + asset_id 
  </script>
</div>

UPDATE And by the way, why do you need to pass fields or params as a local variable, why not to use @fields in your view?

An approach I have used in a couple apps where it's necessary for the client code to use server data is to build a hash and render it into a json literal on the page and have all my JS reference that object. It's the same approach as mentioned above but it's a bit cleaner because you don't have to mix a lot of server tags into your JS code. Easier to read and maintain.

What wrong with this

<div id="panel">
  <script>
    var fields = fields
    var asset_id = <%= asset_id %> 
    alert('Invalid values for ' + fields )
    window.location = "../assets/" + asset_id 
  </script>
</div>

Now you can pass data to html for advance thing you can use something like gon check out gon gem it might help

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