respond_to更改响应类型

respond_to更改响应类型

问题描述:

我正在通过ajax调用控制器的create操作,因此当对象成功保存时,会触发js响应。但是,如果由于验证而导致对象无法保存,那么我希望响应为html。我希望通过不返回其他块中的js响应来实现此目的(请参阅下面的代码),但这会产生406不可接受的错误。respond_to更改响应类型

有关如何做到这一点的任何想法?

我也可能注意到,我为什么要这么做的原因是因为我不能确定如何在验证失败时建立一个适当的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 

如果您特别要求在URL中的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 

这样一来,如果您不指定任何格式的请求时,它会先打JS,如果是一个XHR请求(即,一个AJAX请求),而如果有错误,它会返回HTML,无论如何。

这有道理吗?

+0

啊,这正是我对这种情况所追求的!谢谢=] – 2010-07-19 22:05:01