用Ajax读取xml文件的简单例子
程序员文章站
2024-01-07 20:59:22
到此就可以就发送请求读取服务器端的xml数据了,最后要做的就是处理数据了。 关于xmlhttprequest对象,请参考about xmlhttpreq...
到此就可以就发送请求读取服务器端的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>