ajax请求xml

来源:互联网 发布:剑网3脸型数据非法 编辑:程序博客网 时间:2024/04/28 06:32

books.htm

<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
var txt,x,i;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

//当xmlhttp.send();调用此方法,分别调用4次就是readyState有4个状态
xmlhttp.onreadystatechange=function(){

  //xmlhttp.readyState=0 未初始化 : 1  读取中;  2  已读取; 3  交互中;  4完成;

 //xmlhttp.status: 404 表示文件没有找到;200 服务器数据返回成功; 0 表示本地数据返回成功;

  if (xmlhttp.readyState==4 && xmlhttp.status==200)
  {
        xmlDoc=xmlhttp.responseXML;
        txt="";
        x=xmlDoc.getElementsByTagName("title");
        for (i=0;i<x.length;i++)
        {
             txt=txt + x[i].childNodes[0].nodeValue + "<br />";
        }
    document.getElementById("myDiv").innerHTML=txt;
    }
  }
xmlhttp.open("GET","books.xml",true);
xmlhttp.send();
}
</script>
</head>

<body>

<h2>My Book Collection:</h2>
<div id="myDiv"></div>
<button type="button" onclick="loadXMLDoc()">获得我的图书收藏列表</button>
 
</body>
</html>


books.xml文件

<?xml version="1.0" encoding="ISO-8859-1"?>
<!--  Copyright w3school.com.cn -->
<!-- W3School.com.cn bookstore example -->
<bookstore>
<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="web" cover="paperback">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
<book category="web">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
</bookstore>

 

说明:

1.在服务器访问时,上面代码是可以正常运行的

 

2.如果在本地访问的话,就要修改

if (xmlhttp.readyState==4 && xmlhttp.status==200)

改为

if (xmlhttp.readyState==4 && xmlhttp.status==0)

因为0表示本地访问

即使这样也只能在firefox下正常运行  ie 8  不容许本地访问,

ie6下是可以的,但是这段代码

xmlDoc=xmlhttp.responseXML;

var length = xmlDoc.getElementsByTagName("title").length;

length 是0,取不到值,写成下面的形式就可以了。不知道为什么,高手指点一下?

var xmlObj = new ActiveXObject("Msxml2.DOMDocument");
 xmlObj.loadXML(xmlhttp.responseText);
var length = xmlObj.getElementsByTagName("title").length;

 

3  常犯错误

经常会有xml写错的情况,浏览器是很好的查错工具,直接把xml放到浏览器中运行。