I am rendering json into an html data attribute and using jquery.data to read the attribute. I am expecting $('[data-attribute]').data('attribute') to parse the json and return an object but it intermittently returns a string instead.
location.html.erb
<div data-location="<%= render 'location_json' %>">
location_json.erb
<%= @location.to_json(
only: [:id, :name, :lat, :lng],
method: [:display_name]) %>
location.js
var location = $('[data-location]').data('location')
I suspect an encoding/escaping problem, any ideas?
ERB was intermittently adding newlines which resulted in a json string that jquery.data wouldn't parse. For example, this parsed correctly:
<div data-location="{name":"Bandido's"}">
But this did not (note trailling double quote on newline):
<div data-location="
{name":"Bandido's"}
">
To prevent ERB from adding newlines, add a dash before the closing ERB tag
-%>
Solution:
<div data-location="<%= render 'location_json' -%>">
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.