我一直致力于一个函数getxml
,它创建了一个在xml文件中找到的所有专辑/曲目的关联数组:
function XMLload() {
jQuery.post(url, function(data) {
getxml(data);
}, 'xml');
}
function dataFromTag(node, t) {
var d = node.getElementsByTagName(t);
if (d.length == 0) return ('');
return (d[0].firstChild.nodeValue);
}
jQuery(document).ready(XMLload);
var url = 'music.xml';
function getxml(xmldoc) {
xmlalbums = xmldoc.getElementsByTagName('album');
for (var i = 0; i < xmlalbums.length; i++) {
title = dataFromTag(xmlalbums[i], 'title');
artist = dataFromTag(xmlalbums[i], 'artist');
artwork = dataFromTag(xmlalbums[i], 'artwork');
var xmltracks = xmlalbums[i].getElementsByTagName('track');
var tracks = []
for (var j = 0; j < xmltracks.length; j++) {
song = dataFromTag(xmltracks[j], 'title');
mp3 = dataFromTag(xmltracks[j], 'mp3');
tracks[song] = mp3;
}
albumlist[title] = [artist, artwork, tracks];
}
// call pageLoad();
pageLoad();
}
xml文件采用以下格式:
<albums>
<album>
<title></title>
<artist></artist>
<artwork></artwork>
<track>
<title></title>
<mp3></mp3>
</track>
<track>
<title></title>
<mp3></mp3>
</track>
<track>
<title></title>
<mp3></mp3>
</track>
<track>
<title></title>
<mp3></mp3>
</track>
</album>
</albums>
我现在正尝试使用以下详细信息对 *。js 文件执行相同操作。但我不知道如何重新解释代码,以避免更改我的其余代码。知道我怎么能做到这一点? js文件采用以下格式:
var albums=
[
{ "title":"",
"artist":"",
"artwork":"",
"tracks":[
{"title":"","mp3":".mp3",
"lyrics":""},
{"title":"","mp3":".mp3",
"lyrics":""},
{"title":"","mp3":".mp3",
"lyrics":""},
{"title":"","mp3":".mp3",
"lyrics":""},
]
},
{ "title":"",
"artist":"",
"artwork":"",
"tracks":[
{"title":"","mp3":".mp3",
"lyrics":""},
{"title":"","mp3":".mp3",
"lyrics":""},
{"title":"","mp3":".mp3",
"lyrics":""},
{"title":"","mp3":".mp3",
"lyrics":""},
]
},
]
答案 0 :(得分:2)
您的var albums
有几个问题(额外的逗号,请检查http://jsonlint.com/以验证它)。但除此之外,它是一个有效的JSON对象。
var albums=
[
{ "title":"",
"artist":"",
"artwork":"",
"tracks":[
{"title":"","mp3":".mp3",
"lyrics":""},
{"title":"","mp3":".mp3",
"lyrics":""},
{"title":"","mp3":".mp3",
"lyrics":""},
{"title":"","mp3":".mp3",
"lyrics":""}
]
},
{ "title":"",
"artist":"",
"artwork":"",
"tracks":[
{"title":"","mp3":".mp3",
"lyrics":""},
{"title":"","mp3":".mp3",
"lyrics":""},
{"title":"","mp3":".mp3",
"lyrics":""},
{"title":"","mp3":".mp3",
"lyrics":""},
]
}
];
for (var i = 0; i < albums.length; i++) {
title = albums[i].title;
artist = albums[i].artist;
artwork = albums[i].artwork;
var tracks = []
for (var j = 0; j < albums[i].tracks.length; j++) {
song = albums[i].tracks[j].title;
mp3 = albums[i].tracks[j].mp3;
tracks[song] = mp3;
}
albumlist[title] = [artist, artwork, tracks];
}