<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script>
var xhr=initAjax();
function initAjax()
{
if(window.XMLHttpRequest)
{
return new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
try
{
return new ActiveXObject("Msxml2.XMLHttp");
}
catch(e)
{
try
{
return new ActiveXObject("Microsoft.XMLHttp");
}
catch(e)
{
//return undefined
alert("Your browser doesn't support AJAX!");
}
}
}
}
function showInfo()
{
//var xhr=new ActiveXObject("Msxml2.XMLHttp");
if(xhr!=null)
{
xhr.onreadystatechange=xhrStateChange;
xhr.open("GET","info.xml",true);
xhr.send(null);
} }
function xhrStateChange()
{
if(xhr.readyState==4)
{
document.getElementById("infoDiv").innerHTML=xhr.responseText;
}
else if(xhr.readyState==3)
{
document.getElementById("infoDiv").innerHTML="Loading...";
} }
</script>
</head>
<body>
<input type="button" value="click me" onclick="showInfo()">
<div id="infoDiv"></div>
</body>
</html>
initAjax函数实现了对浏览器的兼容(IE5,6), 不过现在ActiveX技术早已过时, 被浏览器默认禁用.
showInfo函数中将xhrStateChange函数绑定到onreadystatechange事件, 注意这种绑定方式不支持传参(只写函数名不能加括号)!!!而且这句代码写在函数外也是可以的.结果如下
第49行如果把innerHTML改为innerText, 则将不考虑xml文件中的标签, 内容原样显示, 如下
另外, xhr除了responseText属性, 还有一个属性:responseXml.