码迷,mamicode.com
首页 > Web开发 > 详细

Ajax基本知识(二)

时间:2016-04-27 20:46:39      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:

Step 2 – Handling the server response

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.

Ajax基本知识(二)

标签:

原文地址:http://www.cnblogs.com/guojunru/p/5440186.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!