[英]How to pass a variable from controller to javascript within a view?
I have an array @fields which has text and an id, asset_id. 我有一个@fields数组,其中包含文本和一个id,asset_id。 To pass local variables from controller to view in render we use
为了从控制器传递局部变量以在渲染中查看,我们使用
render(:template => "assets/invalid", :locals => {:asset_id => params[:id], :fields => @fields})
The view is 该视图是
<div id="panel">
<script>
alert('Invalid values for ')
window.location = "../assets/"
</script>
</div>
This should generate a popup box. 这将生成一个弹出框。 However, I want the popup box to redirect to "../assets/asset_id" and also display 'Invalid values for + fields'
但是,我希望弹出框重定向到“ ../assets/asset_id”,并显示“ +字段的无效值”
The following doesn't work, 以下无效
<div id="panel">
<script>
var fields = fields
var asset_id = asset_id
alert('Invalid values for ' + fields )
window.location = "../assets/" + asset_id
</script>
</div>
Could it be as simple as this? 这样简单吗?
<div id="panel">
<script>
var fields = <%= fields.to_json %>
var asset_id = <%= asset_id.to_json %>
alert('Invalid values for ' + fields )
window.location = "../assets/" + asset_id
</script>
</div>
UPDATE And by the way, why do you need to pass fields
or params
as a local variable, why not to use @fields
in your view? 更新顺便说一句,为什么您需要将
fields
或params
作为局部变量传递,为什么不在视图中使用@fields
?
An approach I have used in a couple apps where it's necessary for the client code to use server data is to build a hash and render it into a json literal on the page and have all my JS reference that object. 我在几个应用程序中使用的一种方法,其中客户端代码必须使用服务器数据,这是建立一个哈希并将其呈现为页面上的json文字,并使我的所有JS都引用该对象。 It's the same approach as mentioned above but it's a bit cleaner because you don't have to mix a lot of server tags into your JS code.
与上面提到的方法相同,但是更干净一点,因为您不必在JS代码中混合很多服务器标签。 Easier to read and maintain.
易于阅读和维护。
What wrong with this 这怎么了
<div id="panel">
<script>
var fields = fields
var asset_id = <%= asset_id %>
alert('Invalid values for ' + fields )
window.location = "../assets/" + asset_id
</script>
</div>
Now you can pass data to html for advance thing you can use something like gon check out gon gem it might help 现在,您可以将数据传递给html进行高级操作,可以使用gon检查出gon gem等功能,这可能会有所帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.