我正在尝试使用从 last.fm API 中提取的艺术家姓名和图像制作一个菜单。目前,它可以很好地生成图像和名称列表,除了它在列表顶部打印“未定义”。我已经尝试注释掉使用艺术家姓名/图像填充元素的部分,并让它生成元素,但它仍然打印未定义。我对它所说的未定义完全感到困惑。
首先,它进行 AJAX 调用以获取所需的信息:
if (window.XMLHttpRequest) { // Non-IE browsers
httpRequest = new XMLHttpRequest();
}
else if (window.ActiveXObject) { // IE 8 and older
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
httpRequest.open("GET", 'http://ws.audioscrobbler.com/2.0/?method=chart.gettopartists&api_key=b25b959554ed76058ac220b7b2e0a026&format=json', true);
httpRequest.onreadystatechange = function () {
var done = 4, ok = 200;
// Parse the JSON into JavaScript immediately on receipt
if (httpRequest.readyState == done && httpRequest.status == ok) {
artistList = JSON.parse(httpRequest.responseText);
然后它处理该信息并生成它用 inner.HTML 实现的 HTML
var artistsAndImage = {};
for (var i=0; i < artistList["artists"]["artist"].length; i++) {
var name = artistList["artists"]["artist"][i]["name"];
artistsAndImage[name] = artistList["artists"]["artist"][i]["image"][0]["#text"];
};
var code;
// Generate HTML for sidebar with artist names and iamges
for (var name in artistsAndImage) {
nameid = name.
replace(/ /g, "_").
replace(/&/g, ":amp").
replace(/\+/g, ":plus");
code += "<element id=\"" + nameid + "\" onclick=\"details(this)\">\n<p style = \"cursor:default\">\n <img src=\"" + artistsAndImage[name] + "\" alt=\"alt\" width = \"50\" height = \"50\">\n" + name + "\n</p> </element>\n";
};
document.getElementById("sidebar").innerHTML = "<div style = \"padding:20px\">" + code + "</div>";
“未定义”来自哪里,我该如何解决?您可以在此处查看上传的页面的当前化身:http: //test.yukot.corp.he.net/