Hi Alex, What is it that you're actually trying to do? I don't think its such a good idea to put a JSON string on the client side as it can be manipulated to no end.
Why not just call the JSON object directly from the controller instead? David @davidchua On Fri, Aug 26, 2011 at 1:27 AM, Alex Duck <[email protected]> wrote: > Hi all, > > I'm working on a Backbone.js single page app with Rails 3.1, and in an > attempt to save on HTTP requests, I want to embed initial data set in > a HTML document that is sent back to the browser after successful > login. > > I was thinking I can simply convert my ruby object to JSON, then HTML > escape resulting string of JSON, and then use that as a value for > JavaScript variable. Something like this: > > > <% tags = [{name:"tag1", color:"green"}, {name:"</script><b>I can do > something bad here</b>", color:"red"}] %> > > <script type="text/javascript" charset="utf-8"> > //<![CDATA[ > var tags_list = <%= tags.to_json %>; > // ]]> > </script> > > > However, this escapes all the double quotes in that string, which > triggers a "SyntaxError: Unexpected token &" in Chrome: > > var tags_list = > [{"name":"tag1","color":"green"}, > {"name":"</script><b>I can do something bad > here</b>","color":"red"}]; > > > If I remove the Rails' default HTML escaping with <%=raw tags.to_json > %>, then it returns this: > var tags_list = [{"name":"tag1","color":"green"},{"name":"</ > script><b>I can do something bad here</b>","color":"red"}]; > > which, of course, breaks the HTML document with "</script>". > > I guess what I really want is to tell to_json() method to HTML escape > keys and values inside JSON object(s), instead of it returning the > JSON string unescaped, and then having Rails escape that whole string. > I guess what I need is something like this: > > var tags_list = [{"name":"tag1","color":"green"},{"name":"</ > script><b>I can do something bad here</ > b>","color":"red"}]; > > I thought about storing JSON string in a <script type="application/ > json" id="json_string"> tag, and then doing something like > > $.parseJSON($("#json_string").html()) > > but that also has the same problem of escaping, like in the above > example. > > > Is there any easy (Rails) way to do that? Or am I doing it wrong to > begin with? > > Cheers! > > -- > You received this message because you are subscribed to the Google Groups > "Ruby on Rails: Talk" group. > To post to this group, send email to [email protected]. > To unsubscribe from this group, send email to > [email protected]. > For more options, visit this group at > http://groups.google.com/group/rubyonrails-talk?hl=en. > > -- You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to [email protected]. To unsubscribe from this group, send email to [email protected]. For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

