简体   繁体   中英

Why is data showing undefined?

Could anyone help me with this. The rates in table is showing undefined.

Here's the code,

I want to get rates using fastforex.io api

<!DOCTYPE html>
<html>
<head>
  <title>Currency Conversion</title>
</head>
<body>
  <h1>Currency Conversion</h1>
  <table>
    <tr>
      <th>Currency</th>
      <th>Exchange Rate</th>
    </tr>
    <tr>
      <td>EUR</td>
      <td id="eur"></td>
    </tr>
    <tr>
      <td>GBP</td>
      <td id="gbp"></td>
    </tr>
    <tr>
      <td>CHF</td>
      <td id="chf"></td>
    </tr>
  </table>
  <script>
    // Fetch the exchange rates from the API
    fetch(`https://api.fastforex.io/fetch-multi?api_key=1234567891221&from=USD&to=EUR,GBP,CHF
`)
      .then(response => response.json())
      .then(data => {
        // Update the exchange rates in the table
        document.getElementById("eur").innerHTML = data.EUR;
        document.getElementById("gbp").innerHTML = data.GBP;
        document.getElementById("chf").innerHTML = data.CHF;
      });
  </script>
</body>
</html>

The rates data showing undefined.

enter image description here

If you console.log data or you check the documentation, you can see that the data you really want is in the object results.

So in your last 'then', you want to do something like that:

document.getElementById("eur").innerHTML = data.results.EUR;
document.getElementById("gbp").innerHTML = data.results.GBP;
document.getElementById("chf").innerHTML = data.results.CHF;

Okay, I just looked in documentation , there is one clear mistake in your code.

Example of data you get:

{
  "base": "USD",
  "results": {
    "EUR": 0.93803,
    "GBP": 0.83176,
    "CHF": 0.92473
  },
  "updated": "2022-12-30 13:52:50",
  "ms": 2
}

As you can see, there is results property where all data you need is stored, so all you just need to do is this:

fetch(`https://api.fastforex.io/fetch-multi?api_key=1234567891221&from=USD&to=EUR,GBP,CHF`)
  .then(response => response.json())
  .then(data => {
    let results = data.results
    document.getElementById("eur").innerHTML = results.EUR;
    document.getElementById("gbp").innerHTML = results.GBP;
    document.getElementById("chf").innerHTML = results.CHF;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM