This my controller:
def show
@result = {"data"=>{"8"=>{"typeA"=>{"tier"=>[1,2],"message"=>"message"},"typeB"=>"sto"}}}
respond_to do |format|
format.js
end
end
So in show.js.erb
I want to be able to create a JS object data
that is @result['data']
. But it's really not working... The closest I can seem to get is a string representation, but then JSON.parse
fails to convert it to a JS object because all the characters have been encoded:
console.log("<%= @result['data'] %>")
var data = JSON.parse("<%= @result['data'] %>")
console.log(data)
ACTUAL OUTPUT
> {"8":{"typeA":{"message":"message","tier":[1,2]},"typeB":"sto"}}
> Uncaught SYntaxError: Unexpected token & in JSON at position 1
DESIRED OUTPUT (for second console.log)
> {"8":{"typeA":{"tier":[1,2],"message":"message"},"typeB":"sto"}}
Note I tried to do @result.to_json
, this didn't help
Have you tried
@result.to_json
or j
or escape_javascript
helpers?
var data = JSON.parse("<%= j @result['data'] %>")
Unless you use the raw
view helper , Rails will automatically escape tags.
This should do the trick:
var data = <%= raw(@result.to_json) %>;
console.log(data);
console.log(typeof data);
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.