ruby-on-rails - rand has the same value when wrapped inside erb tag
问题描述
I have a new rails app, with a controller Page. The root path is set to 'page#index'.
The app/views/page/index.html has this code:
<h1>Page#index</h1>
<p>Find me in app/views/page/index.html.erb</p>
<script>
setInterval(() => {
console.log(<%= rand %>)
}, 1000)
</script>
Which is truely a bad practice, but I am just curious to know why the console.log(<%= rand %>)
line prints the same number every time?
解决方案
The template is rendered once. If you look at the source of the page you will see one fixed number in the JS code. Reload the page and it is a different number.
If you want a different number every time the JS function is executed you need to do it in JS:
setInterval(() => {
console.log(Math.random())
}, 1000)
推荐阅读
- python - Is there a hook/function in kivy to run once a widget has been added to the tree like onComponentDidMount
- r - How to aggregate data reactively with shiny by the variables you selected from UI?
- java - Illegal character in path at index , Tomcat SSL connector path
- flutter - 参数类型'列表
'不能分配给参数类型'MaterialColor' - reactjs - 如何在 React js 中渲染和输出数据表
- sql-server - 链接服务器数据库仅由表和视图组成
- php - 从多行文本框中获取数据并利用提交的数据 PHP
- sql-server - 添加 NOT NULL 列而不使用 DEFAULT 但 WITH VALUES
- laravel - 如何比较动态网址?
- microsoft-graph-api - Microsoft Graph Booking Businesses DELETE 操作失败:404 Http 响应代码