标签:
httpRequest.onreadystatechange = nameOfTheFunction;
First, the function needs to check for the state of the request. If the state has the value of XMLHttpRequest.DONE
(evaluating to 4), that means that the full server response has been received and it‘s OK for you to continue processing it.
if (httpRequest.readyState === XMLHttpRequest.DONE) { // everything is good, the response is received } else { // still not ready }
The next thing to check is the response code of the HTTP server response. All the possible codes are listed on the W3C site. In the following example, we differentiate between a successful or unsuccessful AJAX call by checking for a 200 OK response code.
if (httpRequest.status === 200) { // perfect! } else { // there was a problem with the request, // for example the response may contain a 404 (Not Found) // or 500 (Internal Server Error) response code }
Now after you‘ve checked the stated of the request and the HTTP status code of the response, it‘s up to you to do whatever you want with the data the server has sent to you. You have two options to access that data:
httpRequest.responseText — returns the server response as a string of text
httpRequest.responseXML — returns the response as an XMLDocument object you can traverse using the JavaScript DOM functions.
标签:
原文地址:http://www.cnblogs.com/guojunru/p/5440186.html