正确的状态codeS的JSON响应Ajax调用? [英] Proper status codes for JSON responses to Ajax calls?

查看:155
本文介绍了正确的状态codeS的JSON响应Ajax调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,jQuery的使Ajax请求时,有以下两种特殊的回调:

For example, jQuery has the following two particular callbacks when making Ajax requests:

成功:当200 / 2xx状态code随响应发送触发。

success: Fired when a 200/2xx status code is delivered along with the response.

错误:被解雇的时候4XX,5XX,等状态codeS回来的响应。

error: Fired when 4xx, 5xx, etc, status codes come back with the response.

如果用户尝试创建一个新的人的对象,我发回成功后,新创建的对象的JSON重新presentation,从而使JavaScript的获得必须的唯一的ID为新对象,等等。当然,这,发送200状态code。

If a user attempts to create a new "Person" object, I send back a JSON representation of the newly created object upon success, thus giving javascript access to the necessary unique ID's for the new object, etc. This, of course, is sent with a 200 status code.

如果一个用户提交恶意或无效的数据(例如,一个无效的/不完整的名称字段),我想通过JSON发回的验证错误消息。 (我不明白为什么这会是一件坏事)。

If a user submits malformed or invalid data (say, an invalid/incomplete "name" field), I would like to send back the validation error messages via JSON. (I don't see why this would be a bad thing).

我的问题是:在这样做,我应该向 200 状态code,因为我成功地处理他们的无效数据?因此,我会使用jQuery 成功的回调,而只是检查错误...

My question is: in doing so, should I send a 200 status code, because I successfully handled their invalid data? Therefore, I'd be using the jQuery success callback, but simply check for errors...

,我应该使用的 4XX 状态code,也许是错误的请求,因为他们给我的数据是无效的? (因此,使用错误回调做必要的客户端通知)。

Or, should I use a 4xx status code, perhaps 'Bad Request', because the data they sent me is invalid? (and thus, use the error callback to do the necessary client-side notifications).

推荐答案

我同意400错误的请求的响应。

I agree with the 400 Bad Request response.

有关灵感,你可以看一下微博(广泛使用JSON服务),请问这是怎么: https://dev.twitter.com/overview/api/response-$c $ CS

For inspiration you could have a look at how Twitter (widely used JSON service) does this: https://dev.twitter.com/overview/api/response-codes

这篇关于正确的状态codeS的JSON响应Ajax调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆