简体   繁体   English

返回一个不同于我的控制器的200的代码以触发Ajax错误是否被认为是一种好习惯?

[英]Is it considered good practice to return a code different than 200 from my controllers, in order to trigger an ajax error?

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

In the my_json_view I do something like: 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

This way, I can easily hook into the ajax:error event, and easily handle the error case. 这样,我可以轻松地陷入ajax:error事件,并轻松处理错误情况。 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? 是否可以返回其他http代码,以便jQuery知道发生了故障?

Sure. 当然。 That's what error codes are for. 这就是错误代码的用途。 But make sure you choose a proper HTTP status code . 但是请确保选择正确的HTTP状态代码

It is. 它是。 You should always return a status code corresponding to what happened in your action, and there's many cases covered by the status codes . 您应该始终返回与操作中发生的情况相对应的状态代码,并且状态代码涵盖了很多情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 AJAX返回码200,但触发了错误 - AJAX return code 200 but fired error 链接中的tabIndex:0被认为是一种很好的做法,以避免href =“javascript:void(0);”? - Is tabIndex: 0 in links considered a good practice in order to avoid href=“javascript: void(0);”? 嵌套对象是否被认为是好的做法? - Is nesting objects considered good practice? 使用RegEx从URL抓取文件扩展名,以便返回正确的Content-Type-好的做法? - Grab file extension from URL, in order to return correct Content-Type, using RegEx - Good practice? JQuery AJAX:为什么发送了 HTTP 代码 200 并且 AJAX 请求仍然被视为失败 - JQuery AJAX: Why is HTTP-code 200 sent and still AJAX request is considered as failed Jquery AJAX POST调用返回200状态OK但错误 - Jquery AJAX POST call return 200 status OK but error Ajax请求仅返回错误,但状态码为200 OK - Ajax Request Only Returns Error But The Status Code Is 200 OK Codeigniter ajax 状态码显示 200 但显示错误信息 - Codeigniter ajax status code shows 200 but display error message jQuery Ajax问题-即使状态码为200也会出错 - jquery ajax issue - error even if status code is 200 在nodejs模块中,自执行函数是否被视为一种好的做法? - Is self executing function considered a good practice in nodejs module?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM