【问题标题】:Is it considered good practice to return a code different than 200 from my controllers, in order to trigger an ajax error?从我的控制器返回不同于 200 的代码以触发 ajax 错误是否被认为是一种好习惯?
【发布时间】:2012-09-05 05:32:09
【问题描述】:

我有如下代码(它是一个远程表单)

def something
  @user = User.find_by_email(params[:email])
  @success = true
  @error = nil
  if !@user
    @success = false
    @error = "No such user"
  elsif !@user.some_condition
    @success = false
    @error = "User did not pass condition"
  end

  respond_to do |format|
    format.json { render "my_json_view",:status => @success ? 200 : 403 }
  end
end

在my_json_view 我做了类似的事情:

json.response do |json|
  if @success
    json.success true
    # data I need here
  else
    json.success false
    json.error @error
  end
end

这样,我可以轻松地挂钩ajax:error 事件,并轻松处理错误情况。我只是想知道这是多么好的练习。是否可以返回不同的 http 代码,让 jQuery 知道失败了?

【问题讨论】:

    标签: javascript jquery ruby ajax


    【解决方案1】:

    是的。您应该始终返回与您的操作中发生的情况相对应的状态代码,status codes 涵盖了许多情况。

    【讨论】:

      【解决方案2】:

      当然。这就是错误代码的用途。但请确保选择正确的HTTP status code。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-05-04
        • 1970-01-01
        • 2015-03-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多