Why do we check for both
xmlHttpObj.readyS开发者_运维知识库tate =4
and
xmlHttpObj.status = 200
not just
xmlHttpObj.readyState =4
A readyState of 4 means that the request is complete, but a status of 200 means the request was a success. 400 and higher is an error (404 = Not found, 500 = Internal Server Error for example).
In many Ajax applications, you'll see a callback function that checks for a ready state and then goes on to work with the data from the server response.This turns out to be a short-sighted and error-prone approach to Ajax programming. If a script requires authentication and your request does not provide valid credentials, the server will return an error code like 403 or 401. However, the ready state will be set to 4 since the server answered the request (even if the answer wasn't what you wanted or expected for your request). As a result, the user is not going to get valid data and might even get a nasty error when your JavaScript tries to use non-existent server data.It takes minimal effort to ensure that the server not only finished with a request, but returned an "Everything is OK" status code. That code is "200" and is reported through the status property of the XMLHttpRequest object.
To make sure that not only did the server finish with a request but that it also reported an OK status, add an additional check in your callback function of xmlHttpObj.status = 200
精彩评论