[英]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我想使用 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.费率数据显示未定义。
If you console.log data or you check the documentation, you can see that the data you really want is in the object results.如果你console.log数据或者你查看文档,你可以看到你真正想要的数据在object结果中。
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:如您所见,
results
属性存储了您需要的所有数据,因此您只需要这样做:
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;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.