我的视图中有h变量,h变量:
[{"folder"=>"High Risk", "weight"=>"38.8", "stocks"=>[{"id"=>"id3", "name"=>"Indian Oil Corporation Ltd.", "weight"=>"14.4"}, {"id"=>"id5", "name"=>"Atul Auto Ltd.", "weight"=>"13.7"}, {"id"=>"id6", "name"=>"Hindustan Zinc Ltd.", "weight"=>"10.6"}]}, {"folder"=>"Expecting PE ratio", "weight"=>"42.3", "stocks"=>[{"id"=>"id7", "name"=>"Infosys Ltd.", "weight"=>"42.3"}]}, {"folder"=>"from kite", "weight"=>"12.8", "stocks"=>[{"id"=>"id8", "name"=>"Hindustan Unilever Ltd.", "weight"=>"12.8"}]}, {"folder"=>"Low Margin", "weight"=>"6.1", "stocks"=>[{"id"=>"id9", "name"=>"Jindal Steel & Power Ltd.", "weight"=>"6.1"}]}]
这是我在view.erb
中的脚本<script>
if (top.location != location) {
top.location.href = document.location.href ;
}
///Some function giving 'val' value
jQuery.ajax({
data: 'val=' + total_span,
dataType: 'script',
type: 'post',
url: "/portfolio/slide_change"
});
</script>
我有两个疑问:
1)我应该如何以及在哪里声明javascript中的新变量以从此文件中的ruby代码中获取h值?(将方法从ruby传递给javascript)
2)我想把这个变量也发布到反手'val'我怎么能这样做?是否有可能一次发布两个变量或者我需要将h与'val'连接起来吗?
答案 0 :(得分:2)
您可以在ERB中使用ruby变量。假设你的erb中有可变的@stocks,你可以使用<%= @stocks.to_json %>
输出它的JSON表示。所以在你的view.erb中你可以写:
<script>
if (top.location != location) {
top.location.href = document.location.href ;
}
var val = <%= h.to_json %>; //rendered view will have actual array there.
jQuery.ajax({
data: 'val=' + total_span,
dataType: 'script',
type: 'post',
url: "/portfolio/slide_change"
});
</script>