用Ajax读取xml文件的简单例子
(编辑:jimmy 日期: 2024/11/17 浏览:3 次 )
到此就可以就发送请求读取服务器端的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>
下一篇:js统计网页在线时间的脚本