10

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?

1
  • thx Falcon.........it helps me :). I'm facing the same problem. Commented Apr 25, 2012 at 6:16

4 Answers 4

14

JSON is valid Javascript right out of the box, so why not just do:

var js_obj = <%= @rails_obj.to_json %>;
Sign up to request clarification or add additional context in comments.

4 Comments

+1! My brain left me. I cannot believe that i did not see that.
JSON it isn't object - it just a text
@Falcon: JSON is valid JavaScript. It works like this. JSON (JavaScript Object Notation) is a subset of JavaScript's syntax. This is the correct answer. Forget mine.
I got some syntax errors and had to add <%= @rails_obj.to_json.to_s.html_safe %> in order for it to work.
3

I find this to be the best way. Worked everytime

 <%= javascript_tag "var obj = #{@obj.to_json}" %>

Comments

2

You need to escape all single-quotes then. ActionView has a helper for escaping JavaScript: ActionView::Helpers::JavaScriptHelper#escape_javascript

Comments

0

Rails 5.X

controller

def new
      @organization_json = Organization.first().to_json
end

view

<script>
    var organization_json = <%= @organization_json.html_safe %>;
<script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.