作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
所以我一直在研究 Rails Zombies,并且已经到了解释 format.html 和 .json 的部分我的问题是这些代码行是做什么的,我们为什么要有它们?如果我在不使用这些格式代码的情况下编写这些方法或操作,它们就可以正常工作,因为我假设它们默认情况下只是以 html 格式显示?如果有人能弄清楚这段代码到底做了什么,我将不胜感激,我也不完全理解 JSON 是什么。
def create
@zombie = Zombie.new(zombie_params)
respond_to do |format|
if @zombie.save
format.html { redirect_to @zombie, notice: 'Zombie was successfully created.' }
format.json { render :show, status: :created, location: @zombie }
else
format.html { render :new }
format.json { render json: @zombie.errors, status: :unprocessable_entity }
end
end
最佳答案
简单来说:
如果请求需要一个 HTML 页面,它将执行给 format.html
的 block 设置的指令。
如果请求需要 application/json
(比如当您发出 Ajax 请求时),将按照提供给 format.json
的 block 中的指示给出响应。
在深入研究创建任何 Web 服务之前,您应该了解 JSON 的含义。参见 http://www.json.org/
关于html - Ruby On Rails | format.html/json 是做什么用的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44036805/
我是一名优秀的程序员,十分优秀!