Ajax响应-成功/失败

I have seen multiple ways in the past of returning success/failure responses from ajax controller actions from backend services.

Is there an accepted best practice for this?

Im thinking in terms of whether the call was successful and also the transport of any error messages.

  • http codes
  • true / string (which would contain the error message)
  • json encoded object containing success/failure flag + data
  • etc

Ive seen things like the above and also 'success' / 'error' responses etc.

My specific scenario here is a controller say for example testConnectionController. It tests whether a database connection is active or has any issues and reports the status back to the client.

You should definitely follow the recommendations for http response codes. Don't be tempted to ignore setting the response code in favor of some structured json error response. Other than that it is really dependent on the needs of you application. What ever you end up going with it is helpful to be consistent across all of your responses. e.g. If you are going to return an error as json make sure every http end point returns the same structure. That way your client can react in the same way to every error response. Generally speaking there isn't much your client is going to be able to do other than display the error to the user so a simple response like this, with various messages, will cover most cases:

{
    "success" : false,
    "message" : "Terrible things occurred!"
}