Reputation: 1463
in my view i have one object, and want to work with this onject from javascript i try to
var js_obj = jQuery.parseJSON('<%=raw @rails_obj.to_json %>');
it works. but if i have "'" symbols, new string symbols, ,,, in this object all fails.
Have somebody know good approach to do it?
Upvotes: 10
Views: 9617
Reputation: 5848
Rails 5.X
controller
def new
@organization_json = Organization.first().to_json
end
view
<script>
var organization_json = <%= @organization_json.html_safe %>;
<script>
Upvotes: 0
Reputation: 111
I find this to be the best way. Worked everytime
<%= javascript_tag "var obj = #{@obj.to_json}" %>
Upvotes: 3
Reputation: 16274
JSON is valid Javascript right out of the box, so why not just do:
var js_obj = <%= @rails_obj.to_json %>;
Upvotes: 14
Reputation: 30996
You need to escape all single-quotes then. ActionView has a helper for escaping JavaScript: ActionView::Helpers::JavaScriptHelper#escape_javascript
Upvotes: 2