Ajax callbacks not working with Rails 3.0.5 and jQuery 1.5.1

元气小坏坏 提交于 2020-01-01 19:21:12

问题


I've got ajax pagination working with the Kaminari gem on my website but I'm having difficulty getting ajax callbacks working

I'm using jquery-1.5.1, rails 3.0.5 and I have the latest rails.js file

My podcasts.html.haml looks as follows

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

#podcasts
  = render @podcasts

My index.js.erb file looks like this:

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

The pagination side of things works fine, and the pages do indeed load via ajax but I want to do some ajax callbacks and I just can't figure out how to get this working.

I've tried adding numerous variations of the following code to my application.js file but with no success at all:

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

I would expect the code above to fire off an alert once the ajax stuff has finished. Nothing is happening though.

Anyone got any ideas?

PS

The paginate method above, is from the Kaminari gem and it creates the following 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>

回答1:


I was not able to follow exactly your code, but I made a simple test (jquery 1.5.1, rails 3.0.5), and it works for me:

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"

I hope this help.



来源:https://stackoverflow.com/questions/5169628/ajax-callbacks-not-working-with-rails-3-0-5-and-jquery-1-5-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!