如何转换此respond_to选项以使用Rails 3版本?

respond_to do |format| if @user.save format.js { render :nothing => true, :status => :ok, :location => @user } else format.js { render :json => @user.errors, :status => :unprocessable_entity } end end 

我尝试过的所有选项(比如将respond_to :js放在控制器的顶部等)并没有像在这里那样工作。

Rails 3格式:

使用respond_to :json和respond_with (@user)

  respond_to :json # You can also add , :html, :xml etc. def create @user= User.new(params[:user]) #---For html flash #if @user.save # flash[:notice] = "Successfully created user." #end respond_with(@user) end # Also, add :remote => :true, :format => :json to the form. 

尝试在控制器中使用format.json而不是format.js ,并使用:remote => :true, :format => :json以相应的forms。

虽然,我不太确定在这种情况下是否应该使用format.jsonformat.js 。 作为默认的Rails 3脚手架生成带有format.json控制器,你正在做render :json作为响应我相信format.json是正确的方法。 当你返回一块应该执行的JS时,应该使用format.js

您请求的URL应以.json结尾,如下所示: /controller/action.json

如果那是不可能的:

您应该在发送ajax请求时将'accepts'参数设置为'application/json'

在此处搜索如何使用'accepts' : http : //api.jquery.com/jQuery.ajax/

在服务器端:

 format.json { render :json => @user.errors, :status => :unprocessable_entity }