【问题标题】:Ajax callbacks not working with Rails 3.0.5 and jQuery 1.5.1Ajax 回调不适用于 Rails 3.0.5 和 jQuery 1.5.1
【发布时间】:2011-07-07 09:05:11
【问题描述】:

我在我的网站上使用 Kaminari gem 进行了 ajax 分页,但我无法让 ajax 回调正常工作

我使用的是 jquery-1.5.1、rails 3.0.5,并且我有最新的 rails.js 文件

我的podcasts.html.haml 如下所示

#paginator
  = paginate @podcasts, :remote => true

#podcasts
  = render @podcasts

我的 index.js.erb 文件如下所示:

$('#podcasts').html('<%= escape_javascript render(@podcasts) %>');
$('#paginator').html('<%= escape_javascript(paginate(@podcasts, :remote => true).to_s) %>');

分页方面工作正常,页面确实通过 ajax 加载,但我想做一些 ajax 回调,但我不知道如何让它工作。

我尝试将以下代码的多种变体添加到我的 application.js 文件中,但完全没有成功:

$('#paginator a').bind('ajax:success', function(data, status, xhr) {alert("success!");})

我希望上面的代码会在 ajax 内容完成后触发警报。但是什么都没有发生。

有人有什么想法吗?

PS

上面的分页方法来自Kaminari gem,它创建了以下html:

<div id="paginator">
  <nav class="pagination">
    <a href="/podcasts" data-remote="true">Page 1</a>
    <a href="/podcasts?page=2" data-remote="true">Page 2</a>
    <a href="/podcasts?page=3" data-remote="true">Page 3</a>
  </nav>
</div>

【问题讨论】:

  • 我有同样的问题,似乎$('#paginator').html('&lt;%= escape_javascript(paginate(@podcasts, :remote =&gt; true).to_s) %&gt;'); 这一行导致回调停止。如果您将其更改为.html.append,它会给出回调..但不幸的是,有重复的分页链接。你解决了这个问题吗?

标签: ruby-on-rails ruby-on-rails-3 jquery


【解决方案1】:

我无法完全遵循您的代码,但我做了一个简单的测试(jquery 1.5.1,rails 3.0.5),它对我有用:

ajax_controller.rb

class AjaxController < ApplicationController
  def get_data
    respond_to do |format|
      format.js { sleep 1; render :json => "ajax value" }
    end
  end
end

index.html.erb

<%= link_to "get_data", get_data_path, :remote => true, :id => 'request' %>

<div id="response">
</div>

<%= javascript_tag do %>
    $("#response").html("default value");

    $("#request").bind("ajax:success", function(e, data, status, xhr) {
        $("#response").html(data);
    });
<% end %>

routes.rb

    get "ajax/index"
    get "ajax/get_data", :as => "get_data"

希望对你有所帮助。

【讨论】:

  • 嘿@plang,谢谢你,今晚晚些时候我将有机会尝试一下,但这个建议看起来不错,而且很有意义,所以我想我可以用它解决问题。再次感谢,干杯
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-04-04
  • 1970-01-01
  • 2011-09-04
  • 1970-01-01
  • 2015-01-16
  • 2011-07-13
  • 2019-07-06
相关资源
最近更新 更多