gpt4 book ai didi

javascript - Ruby on Rails 在应用程序 Erb 文件内的 Javascript 中嵌入 Ruby 代码

转载 作者:行者123 更新时间:2023-11-28 19:27:12 24 4
gpt4 key购买 nike

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

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

此 current_user_json 是应用程序 Controller 文件中的辅助方法。

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

<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 碰巧有一个包含引号的字段,则您必须转义该引号。如果您没有逃脱,那么您所做的就是一个非常典型的黑客攻击媒介,所以请小心行事。

关于javascript - Ruby on Rails 在应用程序 Erb 文件内的 Javascript 中嵌入 Ruby 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27630975/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com