11

注意:我在这里提出我正在做的逻辑。

我在做什么:

想想我们列出产品和分页的基本索引操作。现在使用 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

索引.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>

索引.js.erb

  jQuery('#products').html("<%= escape_javascript (render :partial => 'products/products' ) %>");
  $('.pagination a').attr('data-remote', 'true');

所以有什么问题:

现在我想对此启用动作缓存。但是 index.js.erb 文件并没有操作 DOM。如果我删除了 remote-true 功能,那么缓存就可以正常工作。

对于动作缓存,我在控制器顶部添加了这一行:

 caches_action :index, :cache_path => Proc.new { |c| c.params }

有什么建议么?

更新:

问题是 jquery 代码没有执行。从这个问题

我发现出了什么问题。jQuery 实际上用 a 包围传入的脚本,以便浏览器评估传入的代码。但是缓存机制只是将代码保存为文本,当再次请求时,它会将代码作为文本返回,但不对其进行评估。因此,需要明确地评估代码

但是这个问题怎么解决??

4

4 回答 4

4

经过一些试验和错误,我想我有一个解决方法。

页面链接

代替

$(function() { $('.pagination a').attr('data-remote', 'true') });

采用

$(function() {
  $('.pagination a').click(function() {
    $.ajax({
      url: this.href,
      dataType: 'script'
    });
    return false;
  });
});

因此应用服务器创建的响应将作为 javascript 运行

控制器

接下来,将您的caches_action线路更改为

caches_action :index, cache_path: proc { |c| c.params.except(:_).merge(format: request.format) }

因为ajax_为某种时间戳附加了一个参数

希望这有效:)

于 2013-02-07T09:32:15.077 回答
3

我看不出使用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');
});

编辑:另外,我在这里更深入地介绍了数据类型属性及其与 Rails 的工作方式:http ://www.alfajango.com/blog/rails-3-remote-links-and-forms-data-用 jquery 输入/

于 2013-02-08T17:52:13.387 回答
1

我想我找到了解决这个问题的方法。我有一个控制器,它具有caches_action使用 format.js 通过 ajax 获取一些数据的操作,但它不能开箱即用。

我发现,尽管请求被传输到服务器,并且服务器正确解析请求并“呈现”index.js.erb模板,但 DOM 中没有任何更新。您的解决方案$.ajaxdataType:'script'我解决了这个问题,但是,我不喜欢用 jquery 绑定到链接上的点击,这应该默认发生......我能够通过将我的更改为使其正常link_to工作这:

= link_to "click me", user_action_path(params), remote: true, data:{type: 'script'}

希望这可以帮助!

于 2017-08-18T16:30:44.143 回答
0

我遇到了同样的问题,但是在我的 3.0.3 应用程序中,使用 :remote => true 我添加了 :'data-type' =>: 脚本并且运行良好。

但是,就我而言,当通过 ajax 加载列表时,我看不到任何改进。

于 2013-08-01T07:49:22.243 回答