简体   繁体   English

在Rails 2.3中的javascript中嵌入Ruby代码

[英]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. 我需要将ruby代码嵌入我的Java脚本中,但是这样做在.rhtml文件中不起作用。 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. 使用一些字符串代替<%= @default_values [:release]%>可以看到预期的行为,任何人都可以让我知道是什么问题,或者在rails 2.3中不允许嵌入红宝石。

Ruby's to_s format will not work on Javascript. Ruby的to_s格式不适用于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. JSON是JavaScript的子集,因此,如果将Ruby对象转换为JSON,则应在JavaScript中正确解释。

require "json"

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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