0

我的视图中有 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)我应该如何以及在哪里声明新变量以从该文件中的 ruby​​ 代码中获取 h 值?(将 h 从 ruby​​ 传递到 javascript 的方法)

2)我想用'val'将这个变量也发布到反手我怎么能做到这一点?是否可以一次发布两个变量,还是需要将 h 与 'val' 连接起来?

4

1 回答 1

2

you can use ruby variables in ERB. assuming you have variable @stocks available in your erb, you can output its JSON representation using <%= @stocks.to_json %>. so in your view.erb you can write:

<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>
于 2013-09-04T16:29:56.593 回答