What response/status code should I send to an AJAX

2019-01-18 06:57发布

I am creating a feature of my web application where a user can "edit-in-place" a record and submit the form via AJAX using jQuery.

When someone is "ajax editing" a record and they submit the form with valid data, I send a 200 status code, which triggers the jQuery AJAX Success function, then ignore the response body (since it was successful, I don't need it), and collapse the form.

When there are form validation errors, I send a 400 status code in order to trigger the jQuery error method, and in the body of the request I specify which fields did not validate.

In a previous StackOverflow question, someone mentioned that it "seemed odd" that I was sending a 400 status code and working with the response body. Is my approach not a best-practice? What would you recommend that I do in this situation?

标签: jquery ajax http
3条回答
贪生不怕死
2楼-- · 2019-01-18 07:21

Using the payload of a 4xx status code is just fine. There's nothing in the HTTP spec saying otherwise.

If you want something more specific than 400, have a look at 422 Unprocessable Entity.

查看更多
男人必须洒脱
3楼-- · 2019-01-18 07:22

For me, HTTP status codes are for signalling at the HTTP layer, not the application layer. I would say the appropriate response to bad data properly submitted (if you see what I mean) is a 200 with an application-layer error code. I use JSON for this. My requests always get back a small JSON message, which always has a flag indicating success/failure at the application level. My wrappers for ajax calls know about this and dispatch as appropriate.

查看更多
别忘想泡老子
4楼-- · 2019-01-18 07:23

I would return 200 with an (application) error page, or the original page with an error option, which triggers an informational panel with the error description.

The reason for this is that the HTTP error codes are for the browser's response to the web server, not for your web application. Keep your application logic separate from what happens when the browser and server talk to each other.

查看更多
登录 后发表回答