Why does calling to_json output javascript that is filled with
In my controller action I am doing:
@user = user.to_json
Then in my view I am doing:
<script type="text/javascript">
<%= @user %>
</script>
And the resulting html is like:
[{"user":{"age":8,....
Why does it contain " everywhere?
In irb it outputs just fine like:
[{\"user\"开发者_如何学编程:{\"age\":8,...
In Rails 3 all output in the views is escaped by default. You used to have to call h(..)
to escape stuff.
You can tell Rails that really what you are outputting is safe and rails doesn't need to worry about it by calling html_safe
:
<script type="text/javascript">
<%= @user.html_safe %>
</script>
The reason for this is this data often comes from your users (people post forms for example), and they can include malicious stuff that you would then output, leading to XSS attacks and the like. Rails 3 took a (somewhat controversial) approach of being extra cautious here.
Here is a good blog post from Yehuda about html_safe
and what's really going on
Try the raw method?
<%= raw @user %>
精彩评论