简体   繁体   中英

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.

In the .html.erb file:

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

In the .js file:

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. However, data-points, which is a JSON object, shows up like only this in the console log:

{

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

Does anyone have a clue what I'm doing wrong?

Quotes. Your generated markup is syntactically invalid html. Attribute value ends prematurely, 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.

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}'

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