gpt4 book ai didi

javascript - 从 Swapi API 获取数据 https ://swapi. co/api/people/

转载 作者:太空宇宙 更新时间:2023-11-04 15:26:32 26 4
gpt4 key购买 nike

我想获取 https://swapi.co/api/people/所有名称和其他详细信息,但当我使用 axios 调用来获取数据时,所有数据均未定义,但如果需要一个名称,我会在控制台中收到 CORS 错误。

let button = document.querySelector("#button");
let name = document.querySelector("#displayDetail");

function getDetail(){
var apiURL="https://swapi.co/api/people";
axios.get(apiURL).then(function(response){
showDetail(response.data);
});
}

function showDetail(data){
name.innerText=data.name;
}

button.addEventListener('click',getDetail);

最佳答案

来自 https://swapi.co/api/people 的 JSON 数据没有 name 成员。相反,它有一个 results 成员,它是一个对象数组,每个对象都有一个 name 成员。

因此,您需要循环访问 data.results 数组以获取每个name:

function getDetail() {
var apiURL = "https://swapi.co/api/people";
axios.get(apiURL).then(function(response) {
showDetail(response.data);
});
}

function showDetail(data) {
for (i = 0; i < data.results.length; i++) {
console.log(data.results[i].name);
}
}
getDetail();
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

但请注意:该 API 端点对结果进行分页;因此,要获取所有名称,请检查 data.next 以获取下一页的 URL,然后使用该 URL 发出新请求以获取下一组结果:

function getDetail(apiURL) {
axios.get(apiURL).then(function(response) {
showDetail(response.data);
});
}

function showDetail(data) {
for (i = 0; i < data.results.length; i++) {
names = names + data.results[i].name + "\n";
// name1.innerText = name1.innerText + "\n" + data.results[i].name;
}
if (data.next) {
getDetail(data.next);
} else {
console.log(names); // name1.innerText = names;
}
}
var names = "";
getDetail("https://swapi.co/api/people");
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

关于javascript - 从 Swapi API 获取数据 https ://swapi. co/api/people/,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47365401/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com