简体   繁体   中英

respond_to change response type

I am calling a controller's create action via ajax so when the object saves successfully, the js response is triggered. However, if the object fails to save due to validation, then I want the response to be html. I hope to achieve this by not returning the js response in the else block (please see code below) but this produces a 406 Not Acceptable error.

Any ideas on how to do this?

I should also probably note that the reason why I want to do this is because I am unsure how to create an appropriate js response if the validation fails...

Thanks in advance!!! =]

Controller create action

respond_to do |format|
  if @person.save
    flash[:notice] = 'Successfully created.'
    format.html { redirect_to(@person) }
    format.js
  else
    flash[:error] = 'There are errors while trying to create a new Person'
    format.html { render :action => "new" }
  end
end

If you are specifically requesting the js format in the URL, then you have to provide JS for your response. One option instead would be to not specify a format in the request, and then just filter your responses for xhr. Like so:

respond_to do |format|
  if @person.save
    flash[:notice] = 'Successfully created.'
    if request.xhr?
      format.js
    end
    format.html { redirect_to(@person) }
  else
    flash[:error] = 'There are errors while trying to create a new Person'
    format.html { render :action => "new" }
  end
end

This way, if you make a request without specifying ANY format, it will hit js first, IF it's an xhr request (ie, an AJAX request), whereas, if there is an error, it will return html, no matter what.

Does that make sense?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM