user2507818 user2507818 - 5 months ago 14
Ajax Question

readyState vs status==200

xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
}


Above code is from:http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp.

Question:

According to this tutorial:

readyState: 4: request finished and response is ready

status: 200: "OK"

When readyState is 4 and status is 200, the response is ready:


since when
xmlhttp.readyState == 4
, response is ready, why do we still need
xmlhttp.status == 200
? what is the difference between
xmlhttp.readyState == 4
and
xmlhttp.status == 200
?

Answer

The status of the response, xhr.status, is (generally) used to determine whether the request was successful or not. xhr.readyState is simply used to determine the state of the request, such as "has not yet been sent" (0), "complete and response received" (4), etc.

The server is responsible for providing the status, while the user agent provides the readyState.

Comments