3

What is a good way to convert some common Ruby objects (like strings, hashes, arrays) into corresponding Javascript objects? For example, jQuery css() accepts a hash as an argument. Suppose I have a Ruby hash like this:

h = {"background-color" => "yellow", "color" => "green"}

I want to embed this ruby object into a string so that it becomes a valid javascript (jQuery) command. My best attempt now is to convert it via json like this:

"$('#foo').css(JSON.parse('#{h.to_json}'));"

but it is not working well. I want a more direct and working way to do it. Is there a good way?

4

1 回答 1

7

无需转换为字符串然后 JSON.parse:

"$('#foo').css(#{h.to_json});"

或者如果你打破它...

var h = #{h.to_json};
"$('#foo').css(h);"

呈现给客户端的内容为:

var h = {"background-color":"yellow","color":"green"};
$('#foo').css(h);
于 2013-04-26T18:57:18.027 回答