这里是一个开始:
先用您的视图的link_to方法创建按钮,例如:
=link_to "delete", "#{invitation_path(invitation)}.json", :method=>:delete, :remote=>true, :class=>"remove", :confirm=>'Are you sure you?'
请注意,我将“.json”附加到我的资源的网址。这只是一个AJAX删除的例子,google link_to来查看参数的含义。这个概念是否让您的HTTP请求的参数:remote设置为true,换句话说,这是从您的浏览器转换为AJAX调用。
其次,写一些JavaScript代码,这样就可以处理什么都是AJAX呼叫你的浏览器将当第1步细节的的link_to用户点击就可以看到这个博客帖子结果:http://www.alfajango.com/blog/rails-3-remote-links-and-forms/
一个例子,从我的网站:
jQuery(function($) {
// create a convenient toggleLoading function
var toggleLoading = function() { $("#loading").toggle() };
$("#pending_invitation")
.live("ajax:loading", toggleLoading)
.live("ajax:complete", toggleLoading)
.live("ajax:success", function(event, data, status, xhr) {
var response = JSON.parse(xhr.responseText)
if (response.result == "ok") {
$(this).fadeOut('fast');
}
else {
var errors = $('<div id="error_explanation"/>');
errors.append('<h2>Pending invitation action error</h2><ul><li>' + response.error + '</li></ul>');
$('#new_invitation_error').append(errors)
}
});
});
在这里你可以看到,我解析返回的JSON和和改变基于该网页的HTML。请注意,此js使用顶部视图中定义的CCS ID和类别,此处不包括该ID。
如果现在要你写自己的控制器来这里吐出JSON是一个例子:
class InvitationsController < ApplicationController
respond_to :html, :json
# other methods here
# ...
def destroy
@invitation = Invitation.find(params[:id])
respond_to do |format|
if @invitation
@invitation.destroy
flash[:success] = I18n.t 'invitations.destroy.success'
format.json { render :json =>{:result => "ok", :message=>"Invitation #{params[:id]} was destroyed", :resource_id=>params[:id] } }
else
format.json { render :json => { :result=>"failed", :error=>"Cannot find Invitation #{params[:id]}", :resource_id=>params[:id] } }
end
end
end
end
希望这有助于。
请参阅[本Railscast](http://railscasts.com/episodes/229-polling-for-changes) – Zabba 2011-04-25 02:06:00
这很有帮助,但我特别寻找JSON示例,而不是使用'getScript( )'。我在Rails方面还不够好,看看这个例子如何适用于我所需要的... – sepiroth 2011-04-25 03:31:57
我也发现这非常难。这里有很多例子,但是他们都假设你想使用'action.js.erb',但我不这样做。我**认为**你正在寻找我一样的东西。如果是这样,我会尝试找到一个例子并回复。 – cbmeeks 2011-04-26 15:49:07