1
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コントローラーの上部に配置するなど)は、このようにうまく機能しません。

4

3 に答える 3

4

Rails 3フォーマット:

reply_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.
于 2011-11-20T14:39:00.203 に答える
2

コントローラーformat.jsonの代わりに、対応するフォームで使用してみてください。format.js:remote => :true, :format => :json

ただし、その場合に使用するかどうformat.jsonかはよくわかりません。format.jsRails 3 のデフォルトのスキャフォールディングではコントローラーが生成され、それに応じて処理をformat.json行っているため、これが正しい方法だと思います。また、実行する必要がある JS の一部を返すときに使用する必要があります。render :jsonformat.jsonformat.js

于 2011-11-20T12:58:20.803 に答える
1

リクエストしている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 }
于 2011-11-20T14:12:29.583 に答える