Rails阿贾克斯·杰森

What does format.json and format.html mean? and how to use this in the client side?

def create
  @user = User.new(params[:user])

  respond_to do |format|
    if @user.save
      format.html { redirect_to @user, notice: 'User was successfully created.' }
      format.js   {}
      format.json { render json: @user, status: :created, location: @user }
    else
      format.html { render action: "new" }
      format.json { render json: @user.errors, status: :unprocessable_entity }
    end
  end
end

It allows your application to respond differently depending on whether the client requests a html response or a javascript/JSON response.

In this case if the @user.save is successful and the request wants a html response then the following code will be executed. {redirect_to @user, notice: 'User was successfully created.'}.

However, if you make the request using javascript or ajax and you want the result as a JSON object the following code will be executed { render json: @user, status: :created, location: @user }.