它是好的做法,以返回code超过200个从我的控制器不同,以触发Ajax错误?我的、它是、控制器、做法

2023-09-10 21:00:59 作者:一刹那的疼痛

我有code像下面的(这是一个远程表格)

I have code like the following ( it's a remote form )

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:误差事件,并轻松处理错误情况。我只是想知道如何很好的做法,这是。它是确定返回不同的HTTP code,将让jQuery的认识有一个失败?

This way, I can easily hook into the ajax:error event, and easily handle the error case. I'm just wondering how good practice this is. Is it ok to return a different http code, so that jQuery will know there was a failure?

推荐答案

当然。这就是错误codeS是。但要确保你选择一个合适的 HTTP状态code 。

Sure. That's what error codes are for. But make sure you choose a proper HTTP status code.