我正在尝试抓取此示例中的任何xml标记。但是,如果我尝试抓取除IE中第一条记录中的数据以外的任何内容,我就无法做到。我可以写什么样的JavaScript来纠正这个问题?
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Get Any XML Tag</title>
<script type='text/javascript' src='http://imaginationeverywhere.info/jslib//dev/jquery-1.5.1.js'>
</script>
<script type="text/ecmascript">
function getData() {
var XMLHTTPRequestObject = false;
if (window.XMLHTTPRequest) {
XMLHTTPRequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
XMLHTTPRequestObject = new ActiveXObject('Microsoft.XMLHTTP');
}
if (XMLHTTPRequestObject) {
XMLHTTPRequestObject.open('GET', 'http://imaginationeverywhere.info/xml/cd_catalog.xml', true);
XMLHTTPRequestObject.onreadystatechange = function () {
if (XMLHTTPRequestObject.readyState == 4 && XMLHTTPRequestObject.status == 200) {
var xmlDocument = XMLHTTPRequestObject.responseXML;
displayArtist(xmlDocument);
}
}
XMLHTTPRequestObject.send(null);
}
}
function displayArtist(xmldoc) {
titleName = xmldoc.getElementsByTagName('TITLE');
artistName = xmldoc.getElementsByTagName('ARTIST');
countryName = xmldoc.getElementsByTagName('COUNTRY');
companyName = xmldoc.getElementsByTagName('COMPANY');
priceName = xmldoc.getElementsByTagName('PRICE');
yearName = xmldoc.getElementsByTagName('YEAR');
displayTitle = "The name of this song title is " + titleName[0].firstChild.nodeValue + ".";
displayArtist = "The name of the artist is " + artistName[0].firstChild.nodeValue + ".";
displayCountry = "The name of the artist country is " + countryName[0].firstChild.nodeValue + ".";
displayCompany = "The name of the artist company is " + companyName[0].firstChild.nodeValue + ".";
displayPrice = "This song costs $" + priceName[0].firstChild.nodeValue + ".";
displayYear= "The year this song was released " + yearName[0].firstChild.nodeValue + ".";
var target = document.getElementById('targetDiv');
target.innerHTML = displayTitle + "<br/>" + displayArtist + "<br/>" + displayCountry + "<br/>" + displayCompany + "<br/>" + displayPrice + "<br/>" + displayYear;
}
</script>
</head>
<body>
<h3>Get Tag Value</h3>
<form action="#">
<input type="button" value='Get the name of the artist' onclick="getData()" />
</form>
<div id="targetDiv" style="width:300px; height:20px">
</div>
</body>
</html>
答案 0 :(得分:1)
我建议使用jQuery - 几乎所有浏览器都兼容。
试试这个:
function getData() {
$.ajax({
url: 'ajax/test.html',
dataType : 'xml',
success: function(data) {
displayArtist(data);
});
}