摘要:AJAX实际上由4种技术构成:JavaScript、CSS、DOM、XMLHttpRequest 前三种技术都是传统web应用中常用的技术,只有XMLHttpRequst在传统web中的应用不是很多,所以就来对XMLHttpRequst做个了解。
首先XMLHttpRequest不是web标准,而是大部分主流浏览器都支持的一种扩展技术。它被认为是一种异步调用的实现技术,因为它本来是被设计在后台取数据用的。在IE中它被作为一个ActiveX控件提供,而其他一些浏览器都提供一些本地API以供调用。
下面是一些关于XMLHttpRequest的基本方法:
1、获取得一个XMLHttpRequest对象:

function getXMLHttpRequest()
{
var xRequest = null;

if (window.XMLHttpRequest)
{
xRequest = new XMLHttpRequest();

} else if (typeof ActiveObject != "undefined")
{
xRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
return xRequest;
}

2、向服务器发送XMLHttpRequest:

function sendRequest(url, params, HttpMethod)
{

if (!HttpMethod)
{
HttpMethod = "POST";
}
var req = getXMLHttpRequest();

if (req)
{
req.open(HttpMethod, url, true);
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
req.send(params);
}
}

3、使用回调方法来监测XMLHttpRequest对象的状态
XMLHttpRequest使用属性readyState来表示它的状态
0 = 未初始化
1 = 读取中
2 = 已读取
3 = 交互中
4 = 完成
在事件驱动开发中我们经常使用回调技术,比如UI设计中的对按键的响应等等。我们可以使用对XMLHttpRequest对象的onreadystatechange属性来设置监视XMLHttpRequest对象的状态的回调方法:

function sendRequest(url, params, HttpMethod)
{

if (!HttpMethod)
{
HttpMethod = "POST";
}
var req = getXMLHttpRequest();

if (req)
{
req.onreadystatechange = onReadStateChage;
req.open(HttpMethod, url, true);
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
req.send(params);
}
}


function onReadyStateChange()
{
//
}


4、完整的例子
<html>
<head>

<script language="JavaScript">
var req = null;
var infos = new Array("init
", "loading
", "loaded
", "running
", "finished
");
var console = null;

function initXMLHttpRequest()
{

if (req == null)
{

if (window.XMLHttpRequest)
{
req = new XMLHttpRequest();
}

else if (typeof ActiveObject != "undefined")
{
req = new ActiveXObject("Microsoft.XMLHTTP");
}
}
}

function sendRequest(url)
{

if (req == null)
{
initXMLHttpRequest();
}

if (req)
{
req.onreadystatechange = onReadyStateChange;
req.open("GET", url, true);
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
req.send(null);
}
}

function onReadyStateChange()
{

if (console == null)
{
console = document.getElementById('console');
}
var state = req.readyState;
var txt;

if (state == 4)
{

if (!req.status == 200)
{
txt = "response:" + req.status;

} else
{
txt = "response:" + req.responseText;
}

} else
{
txt = infos[state];
}
var newline = document.createElement("div");
newline.appendChild(document.createTextNode(txt));
console.appendChild(newline);
}
</script>
</head>
<body>
<div id="console"></div>
<input type="button" onClick="sendRequest('ajax_test.txt')" value="Send Request"/>
</body>
</html>

将上面的代码保存为ajax_text.html文档中,然后在同一路径放一个ajax_test.txt,在这个文本文件写下一行文字,用浏览器打开 ajax_text.html,点击"Send Request"看看发生了什么?
BTW 我只在Firefox中测试过,因为我用的是Linux
学习参考资料:
《AJAX in Action》
AJAX开发简略
AJAX开发简略续一