无法将Javascript变量设置为Ruby变量值

时间:2012-12-02 20:56:45

标签: javascript ruby

我有一个Ruby变量:

@json = [{"lat":37.8690058,"lng":-122.2555342},{"lat":37.8739362,"lng":-122.2653001},{"lat":37.8701101,"lng":-122.2578559}]

当我尝试:

<script type="text/javascript" charset="utf-8">

   var test = <%= @json %>
   console.log(test);

</script>

Firebug告诉我:

invalid property id
var test = [{&quot;lat&quot;:37.869005...707408,&quot;lng&quot;:-122.2545767}]

如何成功设置变量?

2 个答案:

答案 0 :(得分:3)

似乎您的JSON引号正在被HTML实体替换。尝试使用.html_safe

var test = <%= @json.html_safe %> 

如果不能解决,请查看其他帖子,因为我不是红宝石专家,

Don't escape html in ruby on rails

答案 1 :(得分:1)

假设@json是一个Ruby对象:

<%= javascript_tag do %>
  var test = <%= @json.to_json.html_safe %>;
<% end %>