用Ajax读取xml文件的简单例子
作者:
Ajax的原理很简单,就是在客户端创建一个XMLHttpRequest对象(用来与服务器进行异步通信,这就是Ajax的核心,其实我们早就在用异步通信了,只是没把这项技术用在网页设计中而已),为该对象的onreadystatechange 属性添加一个事件,当对象的readyState改变的时候就会引发指定的事件。
到此就可以就发送请求读取服务器端的XML数据了,最后要做的就是处理数据了。 关于XMLHttpRequest对象,请参考About XMLHttpRequest Object一文。
看例子:
//AjaxDemo.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Asynchronous JavaScript And XML</title>
</head>
<body>
<script type="text/javascript">
var xmlHttp=null;
function readyStateChangeHandle()
{
if(xmlHttp.readyState==4)
{
if(xmlHttp.status==200)
{
var xmlDOM=xmlHttp.responseXML;
var xmlRoot=xmlDOM.documentElement;
try
{
var xmlItem=xmlRoot.getElementsByTagName("item");
alert(xmlItem[0].firstChild.data);
}
catch(e)
{
alert(e.message);
}
}
}
}
function ajaxRequest()
{
if(window.XMLHttpRequest)
{
xmlHttp=new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.onreadystatechange=readyStateChangeHandle;
xmlHttp.open("GET","data.xml",true);
xmlHttp.send(null);
}
</script>
<input type="button" onclick="ajaxRequest()" value="Take me to the world of AJAX" />
</body>
</html>
//data.xml
<?xml version="1.0" encoding="GB2312" ?>
<root>
<item>Welcome to the world of AJAX(Asynchronous JavaScript And XML)!</item>
</root>
看例子:
//AjaxDemo.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Asynchronous JavaScript And XML</title>
</head>
<body>
<script type="text/javascript">
var xmlHttp=null;
function readyStateChangeHandle()
{
if(xmlHttp.readyState==4)
{
if(xmlHttp.status==200)
{
var xmlDOM=xmlHttp.responseXML;
var xmlRoot=xmlDOM.documentElement;
try
{
var xmlItem=xmlRoot.getElementsByTagName("item");
alert(xmlItem[0].firstChild.data);
}
catch(e)
{
alert(e.message);
}
}
}
}
function ajaxRequest()
{
if(window.XMLHttpRequest)
{
xmlHttp=new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.onreadystatechange=readyStateChangeHandle;
xmlHttp.open("GET","data.xml",true);
xmlHttp.send(null);
}
</script>
<input type="button" onclick="ajaxRequest()" value="Take me to the world of AJAX" />
</body>
</html>
//data.xml
<?xml version="1.0" encoding="GB2312" ?>
<root>
<item>Welcome to the world of AJAX(Asynchronous JavaScript And XML)!</item>
</root>