首页 > 解决方案 > 如何从此 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();

标签: javascriptapihttprequest

解决方案


您可以使用.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.stringifyObject.prototype.toString[Object object]


推荐阅读