- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我想获取 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/
我想获取 https://swapi.co/api/people/所有名称和其他详细信息,但当我使用 axios 调用来获取数据时,所有数据均未定义,但如果需要一个名称,我会在控制台中收到 CORS
我正在构建一个应返回其 ID、缩略图、标题、剧集编号和发行日期的电影网格。 如何映射 Swapi 的这些值? ? (缩略图在 img 文件夹中) ListFilms.js 组件: import Rea
我正在努力从该网站获取 SWAPI(星球大战 API)--> https://swapi.co/填充我的表格 View 单元格,但我对如何抓取字符并用空数组显示它们感到有点困惑。变量“people”起
我正在尝试向服务器端端点添加一个搜索查询,它调用 swapi - Star Wars API https://swapi.co/ 并按姓名列出人员。 这是 App.js 中对后端的 fetch 调用的
我构建一个 React 项目只是为了尝试一些事情,我在使用 SWAPI (Star Wars API) 时遇到问题. 在我的 React 项目中尝试通过 axios 使用他们的 API 时,我不断收到
我正在努力向 http://swapi.co.in 发出成功的请求来 self 的本地主机 creat-react-app 项目。我已将 fetch api 请求放入主容器的 componentDid
我有这个异步函数可以从 Swapi API 获取三个单独的请求来检索数据。但是,我只取回已分页的第一页数据。我知道我必须为 data.next 创建一个循环来发出新请求,但我不确定通过我的函数运行它的
我是一名优秀的程序员,十分优秀!