[英]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.