I'm trying to display an image in a div in html. I used fetch to get the json data from the api : https://collectionapi.metmuseum.org/public/collection/v1/objects/435828. The response gives json date with the image url named "primaryImage". I'm able to display it in text but not as an image.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Image</title>
</head>
<body>
<img id="test">
<script>
let getimage = document.getElementbyId('test');
getimage.src= "data"
fetch('https://collectionapi.metmuseum.org/public/collection/v1/objects/435828')
.then((response) => response.json())
.then((data) => texting.innerText = data.primaryImage);
</script>
</body>
</html>
CodePudding user response:
For your sample page,
replace;
.then((data) => texting.innerText = data.primaryImage);
line with;
.then(data => getimage.src = data.primaryImage);
CodePudding user response:
The process is fairly simple and can be described as follows:
- cache your
image
in a variable so that you can access it later. - make a request to your
API
. - then parse the API response as
JSON
. - then update the
image
source, or specifically thesrc
attribute, as theAPI
response'sprimaryImage
field.
Here's a live demo to illustrate:
// cache the image element so we can access it later
const img = document.getElementById('test');
// make a request to your API
fetch('https://collectionapi.metmuseum.org/public/collection/v1/objects/435828')
// parse the API response as "JSON"
.then(r => r.json())
// update the image's "src" (source)
.then(r => img.src = r.primaryImage);
<img id="test">
You might as well think of adding a loading text or spinner while the image loads but am not going into that as it'll make my answer out of scope.
Just keep in mind that's not always the case as APIs can be different and the way they return their response can change. Anyway, most case will be the same though.
I recommend you take a look at the Fetch API and how it works.