[英]Rails Hash in javascript, access values
I have a following javascript code: 我有以下javascript代码:
<input type="hidden" name="query_form_select_ops" id="query_form_select_ops" value='<%= schema%>' />
<script>
function select_pk2(cell){
var val = $('#query_form_opt_'+cell+'_1').val();
var opts = $('#query_form_select_ops').val();
}
</script>
Example: 例:
schema
is a typical ruby hash: schema
是典型的ruby哈希:
{
"car"=>{"col"=>"blue", "engine"=>"HHd4M"},
"train"=>{"col"=>"black", "engine"=>"8495f"}
}
The variable val
has a value "train" and opts
the whole ruby hash 变量val
的值为“ train”,并opts
整个ruby哈希值
To access the col
and engine
of a train
in ruby: schema["train"]. 要在ruby中访问train
的col
和engine
:schema [“ train”]。 How can I do the same in javascript? 如何在javascript中做同样的事情?
I have tried: 我努力了:
var select = opts[val]
but it tells me that var in undefined. 但是它告诉我var in undefined。 How can I access the values of a ruby hash in javascript given a hash and one of the keys? 给定哈希值和键之一,如何在javascript中访问ruby哈希值?
Dump schema
hash as a json and then parse it back in javascript. 将schema
哈希值转储为json,然后使用javascript解析回来。 Something like this: 像这样:
<input type="hidden" name="query_form_select_ops" id="query_form_select_ops" value='<%= schema.to_json %>' />
And script: 和脚本:
function select_pk2(cell){
var val = $('#query_form_opt_'+cell+'_1').val();
var opts = JSON.parse($('#query_form_select_ops').val());
}
This way you should be able to access values in the way you want. 这样,您应该能够以所需的方式访问值。
Each individual value of the hash in your example is hash as well, so you can access them by using proper keys. 您的示例中哈希的每个单独值也都是哈希,因此您可以使用适当的键来访问它们。 Like this: 像这样:
opts['car']['col'];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.