【问题标题】:Ajax not being loaded to the view rails 3 will_paginateAjax 未加载到视图 Rails 3 will_paginate
【发布时间】:2012-12-09 16:52:22
【问题描述】:

我正在尝试使用 will_paginate gem 实现 Ajax 调用,我发现本指南 http://ramblinglabs.com/blog/2011/11/rails-3-1-will_paginate-and-ajax 似乎是一个简单的解决方案,尽管它包含我不熟悉的咖啡脚本

我的代码如下

我的观点

<div class="container">
 <div class="row">
  <div id="userRecipes">
   <%= render partial: 'userrecipes' %>
 </div>
</div><!--/row-->

我的部分(用户食谱)

 <% @recipes.each do |r| %>
  <div class="span3">
   <div class="thumbnail">
    <%= image_tag r.avatar.url(:myrecipes) %>
   </div>
   <h4><%= link_to r.dish_name, r %></h4>
   <hr>
    <p><%= truncate r.description, :length => 90 %></p>
    <p><%= link_to "Edit Recipe", edit_recipe_path(r.id) %></p>
    <p><%= link_to "Delete Recipe", recipe_path(r.id), :confirm => "Are you sure?", :method => :delete %></p>
    <p><%= link_to "Add to favorites",  {:controller => 'favourites', :action => 'create', :recipe_id => r.id}, {:method => :post } %></p>
   </div><!--/span3-->
   <% end %>
   <%= will_paginate @recipes %>

userrecipes.js.erb 文件

$('#userRecipes').html('<%= escape_javascript(render partial: 'userrecipes') %>');
$.setAjaxPagination();

咖啡脚本

$ ->
$.setAjaxPagination = ->
$('.pagination a').click (event) ->
  event.preventDefault()
  loading = $ '<div id="loading" style="display: none;"><span><img src="/assets/loading.gif" alt="cargando..."/></span></div>'
  $('.other_images').prepend loading
  loading.fadeIn()
  $.ajax type: 'GET', url: $(@).attr('href'), dataType: 'script', success: (-> loading.fadeOut -> loading.remove())
  false

  $.setAjaxPagination()

当我单击下一个锚标记以显示下一组结果时,页面保持原样并且不会出现新内容

当使用控制台查看是否有任何错误时,我可以看到任何错误,输出是

GET http://localhost:3000/my_recipes?page=2&_=1355055997639

我错过了什么吗?

在控制台中检查响应的同时,它还显示正在加载要加载的新配方,但视图中没有发生任何事情

欢迎指点

谢谢

【问题讨论】:

  • 您能否在您的 userrecipes.js.erb 文件中添加console.log("js response received") 行,然后在点击分页后检查浏览器控制台(firebug 等),看看是否打印出来...跨度>
  • 好的,我已经这样做了,但我在回复中看不到它?发生了什么事?
  • 在您的控制台中看到GET 请求。检查它会向您显示请求所在的控制器和操作..它是否显示格式为#html 或#js跨度>
  • “主”视图模板的文件名是什么?是index.html.erb吗?如果是这样,您可能需要将 js 模板命名为 index.js.erb 而不是 userrecipes.js.erb(或在控制器中渲染 userrecipes.js.erb)。
  • 文件名为 my_recipes.html.erb

标签: ruby-on-rails ajax ruby-on-rails-3 jquery will-paginate


【解决方案1】:

will_paginate 创建的链接是html链接...

使用以下代码

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

为它们添加 data-remote true 属性,以便它们向服务器发出js 请求...

【讨论】:

  • 对于基本问题很抱歉,但我应该把它放在哪里,在 js.erb 文件中?还是在咖啡脚本中?
  • 从您的视图中调用此 js 代码,或者在它的文档就绪功能中调用部分用户配方..
【解决方案2】:

您应该将其添加到 js.erb 文件中。

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

这应该可以。

【讨论】:

    猜你喜欢
    • 2012-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-10
    相关资源
    最近更新 更多