简体   繁体   中英

Rails - passing data hash from Ruby to JS via js.erb file

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

  > {&quot;8&quot;:{&quot;typeA&quot;:{&quot;message&quot;:&quot;message&quot;,&quot;tier&quot;:[1,2]},&quot;typeB&quot;:&quot;sto&quot;}}

  > 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM