[英]respond_to change response type
我通过ajax调用控制器的create动作,因此当对象成功保存时,将触发js响应。 但是,如果对象由于验证而无法保存,那么我希望响应为html。 我希望通过不在else块中返回js响应(请参见下面的代码)来实现此目的,但这会产生406 Not Acceptable错误。
有关如何执行此操作的任何想法?
我可能还应该注意,我想这样做的原因是因为我不确定验证失败时如何创建适当的js响应...
提前致谢!!! =]
控制器创建动作
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
如果您在网址中明确要求js格式,则必须提供JS作为响应。 相反,一种选择是不在请求中指定格式,然后仅过滤xhr的响应。 像这样:
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
这样,如果您在没有指定ANY格式的情况下发出请求,则如果是xhr请求(即AJAX请求),它将首先打js,而如果有错误,无论如何都将返回html。
那有意义吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.