Reputation: 28154
For years I have used the following expression to test for xmlHttpRequest success in JavaScript:
(xhr.status==200)
However recently I came across a REST service that returns a different success code (201
) for some methods. So I plan to change my expression to:
(xhr.status==200||xhr.status==201)
Does this cover the most usual cases, or am I still missing something? And is there a better way to test for xhr success?
Upvotes: 1
Views: 2988
Reputation: 115980
You can verify that the HTTP request completed successfully (i.e., without network failure or origin-based security issues) by checking that the readystate
of the request is equal to xhr.DONE
(i.e., 4
).
Determining whether a network-successful HTTP response represents a "successful" application-level action is partially a per-application question (did the application respond how you expect?), but the 2XX
status codes are grouped in section 10 of RFC 2616 as "Successful" HTTP responses.
Therefore, if you want to test generally for a "success"-type response, test for a status between 200
and 299
, inclusive.
Based on a comment by @dfsq, jQuery also includes 304
as a possible "success" response, because it means that there was no application error and nothing has changed about the resource. Unlike other 3XX
responses, 304
is terminal, so the client has completed the request action and does not need to request another resource in a redirect.
Upvotes: 3