简体   繁体   English

当我的JSON数据作为数据属性从erb传递给Javascript时,为什么会丢失?

[英]Why does my JSON data get lost when passed as a data attribute from erb to Javascript?

I try to pass some stuff (among which a JSON object) from the Ruby part of my Rails application to a Javascript file, and try to do so using the HTML data attributes. 我尝试将Rails应用程序的Ruby部分中的一些内容(其中包括一个JSON对象)传递给Javascript文件,并尝试使用HTML数据属性来实现。

In the .html.erb file: 在.html.erb文件中:

<div id='myDiv' data-points="<%=raw @points.to_json%>" data-unit-id="<%=@unit_id%>" >
</div>

In the .js file: 在.js文件中:

var myDiv = document.getElementById("myDiv");
console.log(map_canvas.getAttribute("data-unit-id"));
console.log(map_canvas.getAttribute("data-points"));

Data-unit-id does show up correctly in the console log. Data-unit-id确实正确显示在控制台日志中。 However, data-points, which is a JSON object, shows up like only this in the console log: 但是,作为JSON对象的数据点仅在控制台日志中显示为:

{

When I log <%=raw @points.to_json%> from the html.erb side, it shows up fine as well - so the piece of ruby code does its job fine -, so somewhere while getting passed as a data attribute it gets lost (and data-unit-id does not!). 当我从html.erb端登录<%=raw @points.to_json%> points.to_json <%=raw @points.to_json%> ,它也显示得很好-因此这条红宝石代码很好地完成了工作-因此,在某处被作为数据属性传递时丢失(而data-unit-id不会!)。

Does anyone have a clue what I'm doing wrong? 有人知道我在做什么错吗?

Quotes. 行情。 Your generated markup is syntactically invalid html. 您生成的标记在语法上是无效的html。 Attribute value ends prematurely, data-points="{"foo": 1}" . 属性值过早结束, data-points="{"foo": 1}" See? 看到? You think it's an opening quote for key foo , but actually it's closing quote for data-points value. 您认为这是键foo的开头引号,但实际上它是data-points值的结尾引号。

To avoid this, either escape double quotes in the value: 为避免这种情况,请在值中使用双引号转义:

data-points="{\"foo\": 1}"

or use another type of quotes to surround the value 或使用其他类型的引号将值引起来

data-points='{"foo": 1}'

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

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