【问题标题】:Rails Edge Guides, AJAX example- why use both 'format.js' and 'format.json'?Rails Edge Guides,AJAX 示例 - 为什么同时使用“format.js”和“format.json”?
【发布时间】:2013-10-13 23:21:17
【问题描述】:

"Working With Javascript" section of the Rails Edge Guides 中,给出了一个示例,说明如何在“用户”控制器中构建“创建”操作,以便将 AJAX 集成到创建操作中:

# app/controllers/users_controller.rb
# ......
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

我读过here 'format.js' 和 'format.json' 都需要,因为 Javascript 和 JSON 是不同类型的响应。我的问题是,如果在“创建”操作的 if 语句的前半部分都指定了这两种格式,为什么在后半部分也不需要这两种格式?这是否意味着 Javascript 在成功时使用“create.js.erb”文件,但在失败时不使用?

【问题讨论】:

    标签: javascript jquery ruby-on-rails ajax json


    【解决方案1】:

    是的,你是对的。根据浏览指南,看起来你不想在失败的情况下对 js 做任何事情。如果你把

    format.js   {}
    

    同样在失败块中,然后它会尝试执行render @user 部分,无论如何这可能会导致错误。

    如果你真的想在失败的情况下执行一个 js 块,你可以像其他格式一样执行。

    【讨论】:

      猜你喜欢
      • 2021-07-16
      • 1970-01-01
      • 2015-09-14
      • 1970-01-01
      • 2015-03-31
      • 2013-04-01
      • 2015-11-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多