[英]Why is data showing undefined?
誰能幫我解決這個問題。 表中的費率顯示未定義。
這是代碼,
我想使用 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>
費率數據顯示未定義。
如果你console.log數據或者你查看文檔,你可以看到你真正想要的數據在object結果中。
所以在你最后的“然后”,你想做這樣的事情:
document.getElementById("eur").innerHTML = data.results.EUR;
document.getElementById("gbp").innerHTML = data.results.GBP;
document.getElementById("chf").innerHTML = data.results.CHF;
好的,我剛看了文檔,您的代碼中有一個明顯的錯誤。
您獲得的數據示例:
{
"base": "USD",
"results": {
"EUR": 0.93803,
"GBP": 0.83176,
"CHF": 0.92473
},
"updated": "2022-12-30 13:52:50",
"ms": 2
}
如您所見, 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.