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:“I can do
something bad here”, color:“red”}] %>
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>I can do something bad here",“color”:“red”}];
which, of course, breaks the HTML document with “”.
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 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!