Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse ruby object in JavaScript (Rails)

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?

like image 510
Falcon Avatar asked Dec 13 '10 15:12

Falcon


3 Answers

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

var js_obj = <%= @rails_obj.to_json %>;
like image 59
iain Avatar answered Oct 21 '22 03:10

iain


I find this to be the best way. Worked everytime

 <%= javascript_tag "var obj = #{@obj.to_json}" %>
like image 29
Gerson Azevedo Avatar answered Oct 21 '22 03:10

Gerson Azevedo


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

like image 2
jwueller Avatar answered Oct 21 '22 02:10

jwueller