gpt4 book ai didi

html - Ruby On Rails | format.html/json 是做什么用的?

转载 作者:行者123 更新时间:2023-11-28 00:57:31 25 4
gpt4 key购买 nike

所以我一直在研究 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com