var pageCounter = 1;
var animalContainer = document.getElementById("animal-info");
var btn = document.getElementById("btn");
btn.addEventListener("click", function() {
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'https://learnwebcode.github.io/json-example/animals-1.json');
ourRequest.onload = function() {
if (ourRequest.status >= 200 && ourRequest.status < 400) {
var ourData = ourRequest.responseText;
renderHTML(ourData);
} else {
console.log("We connected to the server, but it returned an error.");
}
};
ourRequest.onerror = function() {
console.log("Connection error");
};
ourRequest.send();
pageCounter++;
if (pageCounter > 3) {
btn.classList.add("hide-me");
}
});
function renderHTML(data) {
var htmlString = "";
for (i = 0; i < data.length; i++) {
htmlString += "<p>" + data[i].name + " is a " + data[i].species + "</p>";
}
animalContainer.insertAdjacentHTML('beforeend', htmlString);
}
我已检查过所有内容,但我不知道代码有什么问题...我正在尝试使用Json和ajax动态加载信息
答案 0 :(得分:1)
您没有将数据解析为JSON,因此您需要做的是将“ourData”解析为JSON。删除并将此行添加到您的代码中。
var ourData = JSON.parse(ourRequest.responseText);