Ruby on Rails 将 Ruby Code 嵌入 JavaScript 中的 Application Erb 文

Ruby on Rails Embed Ruby Code in Javascript inside Application Erb File

本文关键字:Ruby 中的 Application Erb JavaScript 嵌入 on Rails Code      更新时间:2023-09-26

我需要帮助在应用程序.html.erb 布局文件中的脚本标记内显示 rails 帮助程序方法的输出。我将以下代码放在结束 html 标记之前:

<script>
    App.ready = function() {
        App.initApp(jQuery.parseJSON("<%= current_user_json %>"));
    }
</script>

此current_user_json是应用程序控制器文件中的帮助程序方法。

上述代码在浏览器(查看页面源代码)中生成的输出为:

<script>
    App.ready = function() {
        App.initApp(jQuery.parseJSON("{&quot;id&quot;:3,&quot;email&quot;:&quot;user5@user.com&quot;,&quot;username&quot;:null}"));
    }
</script>

正确的输出应该是:

<script>
     App.ready = function() {
         App.initApp(jQuery.parseJSON('{"id":3,"email":"user5@user.com","username":null}'))
     }
</script>

如果有人能帮助我,我真的会从过去几天试图解决的这个问题中解脱出来。

更改以下内容:

<%= current_user_json %>

对此:

<%= current_user_json.html_safe %>

请注意,您必须确保您的 json 已正确转义。例如,如果您的current_user_json碰巧有一个带有引号的字段,则必须对该引号进行转义。如果你没有逃脱,那么你正在做的事情是黑客的一个非常典型的攻击媒介,所以要小心。

试试这个

<%= raw current_user_json.to_json %>