I have a Ruby hash which is passed to a hidden field. How do I extract this hash into JavaScript arrays that I can work with? I need to access the key/value pairs in JavaScript.
Use my_awesome_ruby_hash.to_json
and then you can simply either eval
it in js or use parseJSON
. You might need to require 'json'
(not in Rails).
Ruby code:
state = { 'Waiting' => { name: 'Waiting now', color: 'btn-default' },
'Trying' => { name: 'Trying now', color: 'btn-danger' },
'Answered' => { name: 'Answered now', color: 'btn-success' } }
javascript code:
var state = JSON.parse('#{raw(state.to_json)}');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.