我使用脚手架创建了一个ROR项目,只创建了一个基本项目。我如何使用必须从URL获取的json传递数据?
在下面提到的代码中,我必须获取数据(用户名)并通过json发送 - 这就是我想要做的 - 我该怎么办呢?
hotels_controller.rb
**class HotelsController < ApplicationController
# GET /hotels
# GET /hotels.json
def index
@hotels = Hotel.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @hotels }
end
end
# GET /hotels/1
# GET /hotels/1.json
def show
@hotel = Hotel.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @hotel }
end
end
# GET /hotels/new
# GET /hotels/new.json
def new
@hotel = Hotel.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @hotel }
end
end
# GET /hotels/1/edit
def edit
@hotel = Hotel.find(params[:id])
end
# POST /hotels
# POST /hotels.json
def create
@hotel = Hotel.new(params[:hotel])
respond_to do |format|
if @hotel.save
format.html { redirect_to @hotel, notice: 'Hotel was successfully created.' }
format.json { render json: @hotel, status: :created, location: @hotel }
else
format.html { render action: "new" }
format.json { render json: @hotel.errors, status: :unprocessable_entity }
end
end
end
# PUT /hotels/1
# PUT /hotels/1.json
def update
@hotel = Hotel.find(params[:id])
respond_to do |format|
if @hotel.update_attributes(params[:hotel])
format.html { redirect_to @hotel, notice: 'Hotel was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @hotel.errors, status: :unprocessable_entity }
end
end
end
# DELETE /hotels/1
# DELETE /hotels/1.json
def destroy
@hotel = Hotel.find(params[:id])
@hotel.destroy
respond_to do |format|
format.html { redirect_to hotels_url }
format.json { head :no_content }
end
end
end**
如何使用json获取这些数据,如何编写服务器端代码。
在我使用ror脚手架的源代码中,现在我想要如何使用json解析数据
答案 0 :(得分:0)
我无法解释每一个动作,但这是一个例子
def show
user_json = @params[:user] #'{"name": "User1", "age": 35}'
user = json.parse(user_json)
respond_to do |format|
format.html # index.html.erb
format.json { render json: @user }
end
end