显示所有属性,我只需要命名体重增长,眼睛颜色,肤色和性别
url = "https://swapi.co/api/people";
function heroes () {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var data = JSON.parse(xhr.responseText);
console.log(data); // see object
}
document.getElementById('demo').innerHTML = xhr.responseText; // write info
};
xhr.open("get", url, true);
xhr.send();
}

答案 0 :(得分:0)
您首先展示了请求并解析为JSON对象。这是一个好的开始!
现在,您需要迭代每个结果(您可以使用for循环)并渲染属性。
我已经构建了一个示例,这是代码:
<div id="output">
</div>
var url = "https://swapi.co/api/people";
function heroes() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var data = JSON.parse(xhr.responseText);
var tableContent = '<table>'
tableContent += "<thead><tr>";
tableContent += "<td>Name</td>";
tableContent += "<td>Height</td>";
tableContent += "<td>Mass</td>";
tableContent += "<td>Eye Color</td>";
tableContent += "<td>Skin Color</td>";
tableContent += "<td>Gender</td>";
tableContent += "</tr></thead>";
for(var i=0;i<data.results.length;i++) {
var person = data.results[i];
tableContent += "<tr>";
tableContent += "<td>" + person.name + "</td>";
tableContent += "<td>" + person.height + "</td>";
tableContent += "<td>" + person.mass + "</td>";
tableContent += "<td>" + person.eye_color + "</td>";
tableContent += "<td>" + person.skin_color + "</td>";
tableContent += "<td>" + person.gender + "</td>";
tableContent += "</tr>";
}
tableContent += "</table>"
document.getElementById('output').innerHTML = tableContent; // write table
}
// document.getElementById('demo').innerHTML = xhr.responseText; // write info
};
xhr.open("get", url, true);
xhr.send();
}
heroes();
如果你想要see it live,这是一支笔。