简体   繁体   English

response_以更改响应类型

[英]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. 我通过ajax调用控制器的create动作,因此当对象成功保存时,将触发js响应。 However, if the object fails to save due to validation, then I want the response to be html. 但是,如果对象由于验证而无法保存,那么我希望响应为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. 我希望通过不在else块中返回js响应(请参见下面的代码)来实现此目的,但这会产生406 Not Acceptable错误。

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... 我可能还应该注意,我想这样做的原因是因为我不确定验证失败时如何创建适当的js响应...

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. 如果您在网址中明确要求js格式,则必须提供JS作为响应。 One option instead would be to not specify a format in the request, and then just filter your responses for xhr. 相反,一种选择是不在请求中指定格式,然后仅过滤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. 这样,如果您在没有指定ANY格式的情况下发出请求,则如果是xhr请求(即AJAX请求),它将首先打js,而如果有错误,无论如何都将返回html。

Does that make sense? 那有意义吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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