<script type="text/javascript">
function createXHR()
{
var request = false;
try {
request = new XMLHttpRequest();//最重要的对象.
} catch (trymicrosoft) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = false;
}
}
}
if (!request)
alert("Error initializing XMLHttpRequest!");
}
function AjaxTest()
{
var xhr = createXHR();
xhr.onreadystatechange = function () {
if (xhr.readystate == 4) {
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
alert(xhr.responseText);
}
else {
alert("Request was unsuccessful:" + xhr.status);
}
}
};
//必须在调用open()之前指定onreadystatechange事件处理程序,才能确保跨浏览器兼容性.
xhr.open("get", "test.txt", true);
xhr.send(null);
//注意:事件处理程序中使用了xhr对象,没有使用this对象,原因是onreadystatechange事件处理程序的作用域问题.
//如果使用this对象,在有的浏览器中会导致函数执行失败,或者导致异常.因此使用实际的xhr对象实例变量比较靠谱.
}
</script>