0

我正在学习 javascript,在 javascripts 对象中保存 xml 数据时遇到了一些问题。我真的不知道它是一些语法数据还是什么,但我无法让它工作:

<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">

function book(titl,yea,autho,pric){
    this.title=titl;
    this.year=yea;
    this.author=autho;
    this.price=pric;

this.getTitle = getTit;
this.getYear = getYe;
this.getAuthor = getAuth;
this.getPrice = getPri;

}
function getTit(){ return this.title;}
function getYe(){ return this.year;}
function getAuth(){ return this.author;}
function getPri(){ return this.price;}

var i;
var booki;
var booksArray;
var title;
var year;
var author;
var price;

if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.open("GET","books.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
booksArray = new Array();

    for(i=0;i<30;i++){
        title=xmlDoc.getElementsByTagName("title")[i].childNodes[0].nodeValue;
        year=xmlDoc.getElementsByTagName("year")[i].childNodes[0].nodeValue;
        author=xmlDoc.getElementsByTagName("author")[i].childNodes[0].nodeValue;
        price=xmlDoc.getElementsByTagName("price")[i].childNodes[0].nodeValue;
        booki = new book(title,year,author,price);
        booksArray[i]=booki;
}

for(i=0;i<30;i++){
title= booksArray[i].getTitle;
year= booksArray[i].getYear;
author= booksArray[i].getAuthor;
price= booksArray[i].getPrice;
document.write(title);
document.write(author);
document.write(year);
document.write(price);

}


</script>
</body>
</html>

好吧,我在这里要做的是将 xml 数据存储在一个对象中,然后存储在一个数组中。之后,我将使用对象的方法显示数据。我知道数据加载良好,但以防万一这里是 xml 文件:

<?xml version="1.0" encoding="ISO-8859-1"?>
<!-- Edited by XMLSpy® -->
<bookstore>
<book category="COOKING">
<title lang="en">lorem ipsum</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</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>
<book category="WEB">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>

知道我做错了什么吗?谢谢!

4

0 回答 0