san*_*xus 6 javascript json caching ruby-on-rails
我很困惑如何在我的rails(2.3.5)应用程序中使用json.这些是我需要的元素:
使用辅助方法(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>
Run Code Online (Sandbox Code Playgroud)
问题:如何缓存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
}
});
Run Code Online (Sandbox Code Playgroud)
问题:第二个请求发送到服务器...
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>
Run Code Online (Sandbox Code Playgroud)
问题:如何将该脚本的结果传递给我可以在模板中呈现数据的javascript中使用的变量?
在B和C的情况下,需要在控制器中包括帮助器(计算json数据的方法),这是非常难看的解决方案.
什么应该是正确的解决方案?哪种方法适合这种需求?
谢谢你的所有建议.
san*_*xus 23
没有回复,但我找到了解决方案.对于那些可能遇到类似问题的人来说,也许会为某些人节省时间......
我使用了方法A和Rails缓存.我有一个辅助方法
def footer
return Rails.cache.fetch('footer', :expires_in => 4.hours){
caluclate_data_with_other_methods.to_json
}
end
Run Code Online (Sandbox Code Playgroud)
只是这个...
| 归档时间: |
|
| 查看次数: |
3077 次 |
| 最近记录: |