当前位置: 移动技术网 > IT编程>脚本编程>Ajax > 用Ajax读取xml文件的简单例子

用Ajax读取xml文件的简单例子

2017年12月12日  | 移动技术网IT编程  | 我要评论
到此就可以就发送请求读取服务器端的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>

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网