这是一个开始:
首先在视图中使用 link_to 方法创建按钮,例如:
=link_to "delete", "#{invitation_path(invitation)}.json", :method=>:delete, :remote=>true, :class=>"remove", :confirm=>'Are you sure you?'
请注意,我将“.json”附加到我的资源的 url。这只是一个AJAX删除的例子,google link_to看参数的意思。如果您使用参数 :remote 设置为 true 来发出 HTTP 请求的概念,换句话说,这将转换为来自浏览器的 AJAX 调用。
其次,编写一些 javascript,以便您可以处理当用户单击第 1 步的 link_to 时浏览器将进行的 AJAX 调用的结果。有关详细信息,您可以查看此博客文章: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 和类。
如果您现在想编写自己的控制器来吐出 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
希望这有帮助。