简体   繁体   English

Rails - 通过 js.erb 文件将数据 hash 从 Ruby 传递到 JS

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

This my controller:这是我的 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'] .所以在show.js.erb我希望能够创建一个 JS object data ,即@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:但它真的不起作用......我似乎能得到的最接近的是字符串表示,但是JSON.parse无法将其转换为 JS object 因为所有字符都已编码:

  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注意我尝试做@result.to_json ,这没有帮助

Have you tried你有没有尝试过

@result.to_json

or j or escape_javascript helpers?jescape_javascript助手?

var data = JSON.parse("<%= j @result['data'] %>")

Unless you use the raw view helper , Rails will automatically escape tags.除非您使用raw视图助手,否则 Rails 会自动转义标签。

This should do the trick:这应该可以解决问题:

  var data = <%= raw(@result.to_json) %>;
  console.log(data);
  console.log(typeof data);

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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