An Interest In:
Web News this Week
- March 19, 2024
- March 18, 2024
- March 17, 2024
- March 16, 2024
- March 15, 2024
- March 14, 2024
- March 13, 2024
January 21, 2022 01:29 pm GMT
Original Link: https://dev.to/robsonmuniz16/javascript-fetch-api-simple-example-2ofi
JavaScript Fetch API - Simple Example
Use fetch API to get some data from an any external API
and display it on your website: step-by-step from SCRATCH
Source Code:
HTML
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>JavaScript Fetch API | Simple Example</title> <link rel="stylesheet" href="style.css"> <script src="https://kit.fontawesome.com/fc0bcca8a3.js" crossorigin="anonymous"></script></head><body> <div class="results"> <div class="result" id="cat_result"> <p>Random Cat Placeholder</p> </div> <div class="result" id="dog_result"> <p>Random Dog Placeholder</p> </div> </div> <div class="buttons"> <button id="cat_btn"> <i class="fas fa-cat"></i> Get Cat </button> <button id="dog_btn"> <i class="fas fa-dog"></i> Get Dog </button> </div> <script src="app.js"></script></body></html>
JavaScript
const cat_result = document.getElementById('cat_result');const dog_result = document.getElementById('dog_result');const cat_btn = document.getElementById('cat_btn');const dog_btn = document.getElementById('dog_btn');cat_btn.addEventListener('click', getRandomCat);dog_btn.addEventListener('click', getRandomDog);function getRandomCat() { fetch('https://aws.random.cat/meow').then((res) => res.json()).then((data) => { cat_result.innerHTML = `<img src=${data.file} alt="cat" />`; });}function getRandomDog() { fetch('https://random.dog/woof.json').then((res) => res.json()).then((data) => { dog_result.innerHTML = `<img src=${data.url} alt="dog" />`; });}
Original Link: https://dev.to/robsonmuniz16/javascript-fetch-api-simple-example-2ofi
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To