步骤 2 ? "收到!" --- 处理服务器的响应
当发送请求时,要提供指定处理响应的Javascrīpt函数名.
http_request.onreadystatechange = nameOfTheFunction;
我们来看看这个函数的功能是什么.首先函数会检查请求的状态.如果状态值是4,就意味着一个完整的服务器响应已经收到了,您将可以处理该响应.
if (http_request.readyState == 4) {
// everything is good, the response is received
} else {
// still not ready
}
readyState的取值如下:
0 (未初始化)
1 (正在装载)
2 (装载完毕)
3 (交互中)
4 (完成)
接着,函数会检查HTTP服务器响应的状态值. 完整的状态取值可参见 W3C site. 我们着重看值为200 OK的响应.
if (http_request.status == 200) {
// perfect!
} else {
// there was a problem with the request,
// for example the response may be a 404 (Not Found)
// or 500 (Internal Server Error) response codes
}
在检查完请求的状态值和响应的HTTP状态值后, 您就可以处理从服务器得到的数据了.有两种方式可以得到这些数据:
http_request.responseText ? 以文本字符串的方式返回服务器的响应
http_request.responseXML ? 以XMLDocument对象方式返回响应.处理XMLDocument对象可以用Javascrīpt DOM函数
步骤 3 ? "万事俱备!" - 简单实例
我们现在将整个过程完整地做一次,发送一个简单的HTTP请求. 我们用Javascrīpt请求一个HTML文件, test.html, 文件的文本内容为"I'm a test.".然后我们"alert()"test.html文件的内容.
<scrīpt type="text/javascrīpt" language="javascrīpt">
var http_request = false;
function makeRequest(url) {
http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/xml');
}
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
http_request.onreadystatechange = alertContents;
http_request.open('GET', url, true);
http_request.send(null);
}
function alertContents() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
alert(http_request.responseText);
} else {
alert('There was a problem with the request.');
}
}
}
</scrīpt>
<span
style="cursor: pointer; text-decoration: underline"
ōnclick="makeRequest('test.html')">
Make a request
</span>