How to make AJAX responses work from the Rails side?

£可爱£侵袭症+ 提交于 2019-12-05 05:55:55

问题


The HTML form:

<form id="newsletter" method="post" action="/subscribers" data-remote="true">
    <label for="email">Enter your email:</label>
    <input type="text" name="email" class="text" />
    <p class="btn"><span>Signup</span></p>
</form>

Note the data-remote="true"

The Controller:

class SubscribersController < ApplicationController
  def create
    @subscriber = Subscriber.create(:email      => params[:email],
                                    :ip_address => request.remote_ip )

    respond_to do |format|
      format.js
    end
  end
end

The View (subscribers/create.js.erb)

no clue what goes here to make it return normal AJAX response (or error if it encountered one

1. What do i put in the view to make it return normal ajax response or error? -- Is it even needed to begin with (can I return this without creating such views)

2. Is this the correct way of doing ajax with Rails?


回答1:


This looks exactly like a question that I just answered today for another user... same model names and everything.

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

Also, you shouldn't have to do the unless Subscriber.find_by_email(params[:email]) in your controller. You should just add validates_uniqueness_of :email to the Subscriber model.

In the .erb file that contains the form, you would add the following 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
    });
});



回答2:


A standard respond_to block (this allows both html and js) would be:

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  

So what you have actually looks ok to me. Is it working ok or is there an issue?

The above should work with rails2 and rails3. Rails3 has a more succint syntax (of course) but given you are Rails2 I'll leave that for now.



来源:https://stackoverflow.com/questions/8197019/how-to-make-ajax-responses-work-from-the-rails-side

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