![](/img/trans.png)
[英]How to call javascript function from code behind on button click and store its output and proceed further
[英]how to proceed further with this API
為了復習我的 web 開發技能,我正在嘗試重新學習 API。 我從這個網站得到: https://documenter.getpostman.com/view/10808728/SzS8rjbc?version=latest
在我的 JS 文件中,我有以下代碼:
var requestOptions = {
method: 'GET',
redirect: 'follow'
};
fetch("https://api.covid19api.com/summary", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
而且我看到它記錄了很多數據,但我不確定如何從 API 中獲取特定數據並將其顯示在 HTML 頁面上。
我在 JS 文件中嘗試過這樣的事情:
var requestOptions = {
method: 'GET',
redirect: 'follow'
};
fetch("https://api.covid19api.com/summary", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
let tdeaths = data.global.TotalDeaths;
document.getElementById('tdeaths').innerHTML = tdeaths.toLocaleString('en');
但是我的 HTML 文件上沒有顯示任何內容
您必須將代碼放在.then
語句中。 所以它應該是這樣的:
fetch("https://api.covid19api.com/summary", requestOptions)
.then(response => response.json())
.then(result => {
let tdeaths = result.global.TotalDeaths;
document.getElementById('tdeaths').innerHTML = tdeaths.toLocaleString('en');
})
.catch(error => console.log('error', error));
我看到有兩個問題。
1. 你如何更新data.global.TotalDeaths
? 它將采用初始值,因為 tdeaths 沒有從響應中獲取 output。
2. document.getElementByid
語句將在從 API 檢索值之前運行。 所以在解決了第一個問題之后,你應該像下面這樣寫語句(考慮結果=數據)
.then(result => {
let tdeaths = result.global.TotalDeaths;
document.getElementById('tdeaths').innerHTML = tdeaths.toLocaleString('en');
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.