如何从Rails端使AJAX响应工作?
HTML表单:
注意data-remote="true"
控制者:
class SubscribersController params[:email], :ip_address => request.remote_ip ) respond_to do |format| format.js end end end
视图(subscriber / create.js.erb)
no clue what goes here to make it return normal AJAX response (or error if it encountered one
1.我在视图中放置什么使其返回正常的ajax响应或错误? – 它甚至需要开头(我可以在不创建此类视图的情况下返回此内容)
2.这是使用Rails执行ajax的正确方法吗?
这看起来就像我今天刚刚为另一个用户回答的问题……相同的型号名称和所有内容。
def create @subscriber = Subscriber.new(#your params) respond_to do |format| if @subscriber.save format.js { render :json => @subscriber, :status => :created, :location => @susbscriber } else format.js { render :json => @susbcriber.errors, :status => :unprocessable_entity } end end end
此外,您不应该在控制器中执行unless Subscriber.find_by_email(params[:email])
。 您应该只将validates_uniqueness_of :email
添加到订阅服务器模型。
在包含表单的.erb文件中,您将添加以下javascript:
jQuery(function($) { // create a convenient toggleLoading function var toggleLoading = function() { $("#loading").toggle() }; $("#your-form") .bind("ajax:loading", toggleLoading) .bind("ajax:complete", toggleLoading) .bind("ajax:success", function(event, data, status, xhr) { $("#response").html(data); }); .bind("ajax:failure", function(event, data, status, xhr) { //your code }); });
标准的respond_to块(这允许html和js)将是:
respond_to do |format| if @subscriber.save format.html { redirect_to(@subscriber, :notice => 'Subscriber created.') } format.js # Not redirecting, just spitting out the JSON(js?) response (I believe). else format.html { render :action => "new" } format.js # Not redirecting for js and this time return error response. end end
所以你实际上看起来对我很好。 工作正常还是有问题?
以上内容适用于rails2和rails3。 Rails3有一个更多的succint语法(当然),但鉴于你是Rails2,我现在就离开。