I have a task to get and display in html a particular data from API result (console.log). For now on, I only have a javascript that gets exchange rates with currency conversion. From fetched data I only need currency rate.
var myHeaders = new Headers();
myHeaders.append("apikey", "r4T22n3O14QL7FoG6FzY7FuUHTNXiKAy");
var requestOptions = {
method: 'GET',
redirect: 'follow',
headers: myHeaders
};
//var rslt = console.log(result);
fetch("https://api.apilayer.com/currency_data/convert?to=RUB&from=EUR&amount=1", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
Here is the result I get in console.log and my problem is that I cannot display : 1. anything from that log to HTML and 2. particular data (rates) from that log .
this is the console log I am getting:
{
"success": true,
"query": {
"from": "EUR",
"to": "RUB",
"amount": 1
},
"info": {
"timestamp": 1658378463,
"quote": 56.217115
},
"result": 56.217115
}
I need to get a rates/"quote" as a variable in order to use it elsewhere.
Thank you in advance.
Use response.json()
and then extract the properties that you want into variables.
fetch("https://api.apilayer.com/currency_data/convert?to=RUB&from=EUR&amount=1", requestOptions) .then(response => response.json()) .then(json => { let quote = json.info.quote; document.getElementById("quote").innerText = quote; }) .catch(error => console.log('error', error));
To display value using HTML, you need to use Template literals concept in javascript. You can set elements with a unique ID in HTML. Using HTML DOM Element innerHTML Property and Template Literals you can achieve.
Particular data (rates) from that log:
let rate = result.result;
As I mentioned above you will get the rate result.
Assuming you have something like
<div id="quote"></div>
in your html,
I would do something like this:
.then(response => response.json())
.then(data => { document.getElementById('quote').innerHTML = data.info.quote})
.catch(error => console.log('error', error));
see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
I've got the answer !
const render = data => {
const rate = document.querySelector(".rate")
rate.innerHTML = (data.info.rate).toFixed(2);
}
const init = url => {
fetch(url).then(resp => resp.json()).then(render)
}
init("https://api.exchangerate.host/convert?from=EUR&to=RUB")
and of course this is another API provider, but anyway, this is the simplest way to get and manipulate with currency rate data.
Thanks for everyone's attempt :)
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.