Moh*_*ain 11 ajax caching ruby-on-rails action-caching
注意:我在这里提出一个逻辑我在做什么.
我在做什么:
考虑我们列出产品和分页的基本索引操作.现在使用remote-true选项我启用了基于ajax的分页.到目前为止,事情完美无缺.看看示例代码.
产品控制器:
def index
@products = Product.paginate(:order =>"name ASC" ,:page => params[:page], :per_page => 14)
respond_to do |format|
format.html # index.html.erb
format.json { render json: @products }
format.js
end
end
Run Code Online (Sandbox Code Playgroud)
Index.html.erb
<h1>Products</h1>
<div id="products">
<%= render "products/products" %> // products partial is just basic html rendering
</div>
<script>
$(function(){
$('.pagination a').attr('data-remote', 'true')
});
</script>
Run Code Online (Sandbox Code Playgroud)
index.js.erb的
jQuery('#products').html("<%= escape_javascript (render :partial => 'products/products' ) %>");
$('.pagination a').attr('data-remote', 'true');
Run Code Online (Sandbox Code Playgroud)
所以有什么问题:
现在我想在此上启用动作缓存.但是index.js.erb文件不是在操纵DOM.如果我删除了remote-true功能,那么缓存就可以正常工作了.
对于动作缓存,我在控制器的顶部添加了这一行:
caches_action :index, :cache_path => Proc.new { |c| c.params }
Run Code Online (Sandbox Code Playgroud)
有什么建议?
更新:
问题是jquery代码没有执行.从这个问题
我发现了什么是错的.jQuery实际上用传入脚本包围,以便浏览器评估传入的代码.但是缓存mechansim只是将代码保存为文本,当重新请求时,它将代码作为文本返回但不对其进行评估.因此,需要明确地评估代码
但是如何解决这个问题?
我不明白使用时应该出现什么问题remote: true。其他人建议使用.ajax而不是remote: true,但这正是远程功能的作用,因此应该没有任何区别。
另一个答案具有显式使用 的代码jQuery.ajax,但其代码与远程功能的唯一区别在于它们指定了显式dataType. 不过,你实际上可以做到这一点remote: true。
在 HTML 链接中,您只需指定data-type="script". 或者,根据您发布的 JS,您可以这样做:
$(function(){
$('.pagination a').attr('data-remote', 'true').attr('data-type', 'script');
});
Run Code Online (Sandbox Code Playgroud)
编辑:此外,我在这里更深入地介绍了 data-type 属性及其如何与 Rails 配合使用:http ://www.alfajango.com/blog/rails-3-remote-links-and-forms-data-类型与 jquery/