javascript - 如何从此 API 中提取数据?HttpRequest, JavaScript
问题描述
我怎样才能提取数据?我需要电路名称、日期、比赛名称、回合、季节和时间
var xhr = new XMLHttpRequest;
xhr.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
var json = JSON.parse(xhr.responseText);
var yourData = json.MRData;
document.getElementById('playlist').innerHTML = yourData;
}
};
xhr.open("GET", "http://ergast.com/api/f1/current/next.json", true);
xhr.send();
解决方案
您可以使用.map
比赛数组并为每个比赛返回一个遵循您的模型的对象:
var xhr = new XMLHttpRequest;
xhr.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
const json = JSON.parse(xhr.responseText);
const { MRData: data } = json;
// show the json in HTML
document.getElementById('playlist').innerHTML = JSON.stringify(data, null, 2);
// log circuitName, date, raceName, round, season and time
const { Races: races } = data.RaceTable
const extractList = races.map(({
Circuit: circuit,
date,
raceName,
round,
season,
time,
}) => ({
circuitName: circuit.circuitName,
date,
raceName,
round,
season,
time,
}))
console.log(extractList)
}
};
xhr.open("GET", "http://ergast.com/api/f1/current/next.json", true);
xhr.send();
<pre id="playlist"></pre>
笔记
要在 HTML 中呈现 JSON,您应该使用其他方法对对象进行字符串化,同时将其序列化为此字符串:JSON.stringify
Object.prototype.toString
[Object object]
推荐阅读
- .net-core - 是否可以调用 func 事件?
- java - 即使我的代码适用于样本,但在测试集 1 中得到错误答案(Google Kickstart 2020 Round A)
- reactjs - React JS vs VUE for ERP 使用 Larvel 和 SSR
- java - 如何使用 JGit 库获取 git repo 文件夹中所有文件的 SHA 值列表
- javascript - 更新输入文本字段以依次更新 Primefaces 编辑器上的文本
- excel - VBA Excel选择字符出现后的内容
- css - 我想在 css 中增加背景的宽度,我该怎么做?
- javascript - 有没有办法使用行和列索引更新 ag-grid 中特定单元格的样式?
- r - 如何将 qgraph 图转换为 grob 或以其他方式生成具有多个 qgraph 对象的单个图?
- r - 使用与 igraph.vs 对象列表长度一样多的 for 循环来创建具有它们包含的名称的数据帧