rails 应用程序中使用的 .json 文件是什么?
What is a .json file used for in a rails app?
.json 文件在专业 rails 应用中的具体用途是什么?
我为我的博客创建了一个脚手架,并了解了 postgresql 数据库的 CRUD 操作,但是我只是想知道 format.json
行代码也在脚手架中创建。
def create
@blog = Blog.new(blog_params)
respond_to do |format|
if @blog.save
format.html { redirect_to @blog, notice: 'Blog was successfully created.' }
format.json { render :show, status: :created, location: @blog }
else
format.html { render :new }
format.json { render json: @blog.errors, status: :unprocessable_entity }
end
end
end
JSON是API的常用格式,RailsAPI的常用格式。
当您在控制器中执行 format.json
时,您实际上是在说 "This route/endpoint can respond to JSON requests",而不仅仅是 html 个请求。
在浏览器中查看网站时,您的浏览器会自动发送名为 Accept
的 HTTP Header。如:
Accept: <MIME_type>/<MIME_subtype>
Accept: <MIME_type>/*
Accept: */*
这可以是任意数量的MIME-Types;包括 Accept: application/json
,它会告诉 Rails,它可以用 JSON 响应。
浏览器所做的是沿着 Accept: text/html
发送,它被视为 "Hi, I want the HTML edition of this",从而呈现 format.html
-block。
另请参阅:
.json 文件在专业 rails 应用中的具体用途是什么?
我为我的博客创建了一个脚手架,并了解了 postgresql 数据库的 CRUD 操作,但是我只是想知道 format.json
行代码也在脚手架中创建。
def create
@blog = Blog.new(blog_params)
respond_to do |format|
if @blog.save
format.html { redirect_to @blog, notice: 'Blog was successfully created.' }
format.json { render :show, status: :created, location: @blog }
else
format.html { render :new }
format.json { render json: @blog.errors, status: :unprocessable_entity }
end
end
end
JSON是API的常用格式,RailsAPI的常用格式。
当您在控制器中执行 format.json
时,您实际上是在说 "This route/endpoint can respond to JSON requests",而不仅仅是 html 个请求。
在浏览器中查看网站时,您的浏览器会自动发送名为 Accept
的 HTTP Header。如:
Accept: <MIME_type>/<MIME_subtype>
Accept: <MIME_type>/*
Accept: */*
这可以是任意数量的MIME-Types;包括 Accept: application/json
,它会告诉 Rails,它可以用 JSON 响应。
浏览器所做的是沿着 Accept: text/html
发送,它被视为 "Hi, I want the HTML edition of this",从而呈现 format.html
-block。
另请参阅: