【发布时间】:2011-08-28 20:41:14
【问题描述】:
我对如何在我的 rails (2.3.5) 应用程序中使用 json 感到困惑。这些是我需要的元素:
- html 模板
- json 数据
- javascript在模板中渲染数据(我用PURE)
使用辅助方法(rails 和我自己的方法)计算的 json 数据非常大,并且不会经常更改(通常是页脚、页眉和页面的其他一些部分),因此应该缓存它。正确的做法是什么?
我尝试了 3 种方法。
一个。
- html template and javascript to render data placed in the view html.erb
- method to get json data placed in the helper
<script type="text/javascript">
var data= <%= helper_method %>;
</script>
问题:如何缓存json数据?
B.
- html template and javascript to render data placed in the view html.erb
- method to get json data is a controller action
def footer
expires_in(4.hours)
render :json => { calculated_data }
end
- ajax request in javascript
$.ajax({
type: "GET",
url: "<%=footer_path %>",
success: function(data){
render json data in html template
}
});
问题:第二个请求发送到服务器...
C.
- html template and javascript to render data placed in the view html.erb
- method to get json data is a controller action
def footer
expires_in(4.hours)
render :json => { calculated_data }
end
- data in javascript
<script type="text/javascript" src="<%=footer_path %>">
</script>
问题:如何将该脚本的结果传递给我可以在 javascript 中使用的变量,该变量在模板中呈现数据?
在 B 和 C 的情况下,需要在控制器中包含帮助程序(用于计算 json 数据的方法),这是一个非常丑陋的解决方案。
这应该是什么正确的解决方案?哪种方法适合这种需求?
感谢所有建议。
【问题讨论】:
标签: javascript ruby-on-rails json caching