Ajax回调不适用于Rails 3.0.5和jQuery 1.5.1 [英] Ajax callbacks not working with Rails 3.0.5 and jQuery 1.5.1
问题描述
我在我的网站上使用 Kaminari gem 进行了ajax分页,但是我遇到了困难使ajax回调正常工作
I've got ajax pagination working with the Kaminari gem on my website but I'm having difficulty getting ajax callbacks working
我正在使用jquery-1.5.1,rails 3.0.5,并且具有最新的rails.js文件
I'm using jquery-1.5.1, rails 3.0.5 and I have the latest rails.js file
我的podcasts.html.haml
看起来如下
#paginator
= paginate @podcasts, :remote => true
#podcasts
= render @podcasts
我的index.js.erb文件如下:
My index.js.erb file looks like this:
$('#podcasts').html('<%= escape_javascript render(@podcasts) %>');
$('#paginator').html('<%= escape_javascript(paginate(@podcasts, :remote => true).to_s) %>');
分页功能很好,页面确实可以通过ajax加载,但是我想做一些ajax回调,而我只是想不通如何使它工作.
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.
我尝试将以下代码的多种变体添加到我的application.js文件中,但没有成功:
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!");})
我希望上面的代码在ajax内容完成后会触发警报.没事.
I would expect the code above to fire off an alert once the ajax stuff has finished. Nothing is happening though.
有人有什么主意吗?
上面的分页方法来自 Kaminari gem ,它会创建以下html:
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>
推荐答案
我无法完全遵循您的代码,但是我做了一个简单的测试(jquery 1.5.1,rails 3.0.5),它对我有用:
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"
我希望有帮助.
这篇关于Ajax回调不适用于Rails 3.0.5和jQuery 1.5.1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!