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 =
[{&quot;name&quot;:&quot;tag1&quot;,&quot;color&quot;:&quot;green&quot;},
{&quot;name&quot;:&quot;&lt;/script&gt;&lt;b&gt;I can do something bad
here&lt;/b&gt;&quot;,&quot;color&quot;:&quot;red&quot;}];


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":"&lt;/
script&gt;&lt;b&gt;I can do something bad here&lt;/
b&gt;","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.

Reply via email to