简体   繁体   中英

Embed the Ruby code in javascript in rails 2.3

I have a requirement to embed the ruby code in my java script but doing that is not working in .rhtml file. I do this in the following way.

    function set_default_values(){
        var ele =  <%= @default_values[:release] %> ;
        var elmnt = document.getElementById("release");
        for(var i = 0; i < elmnt.options.length; i++){
          if( elmnt.options[i].value == ele ) {
               elmnt.selectedIndex = i;
               break;
           }
        }
     }

Using some string in place of <%= @default_values[:release] %> the expected behavior can be seen, can any one let me know whats the issue or the embedding of ruby is not allowed in rails 2.3.

Ruby's to_s format will not work on Javascript. You need to convert it. JSON is a subset of JavaScript, so if you convert a Ruby object to JSON, that should be correctly interpreted in JavaScript.

require "json"

...
<%= @default_values[:release].to_json %>
...

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