Last active
September 21, 2023 16:26
-
-
Save ShilGen/ba1b878bf3c940244a85baea9e79456e to your computer and use it in GitHub Desktop.
JS Fetch GET example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="utf-8"> | |
<title>FETCH JS</title> | |
</head> | |
<body> | |
<h1>Authors</h1> | |
<ul id="authors"></ul> | |
<script> | |
const ul = document.getElementById('authors'); | |
const url = 'https://randomuser.me/api/?results=10'; | |
// функции для создания элементов | |
function createNode(element) { | |
return document.createElement(element); | |
} | |
//функция добавления дочернего элемента | |
function append(parent, el) { | |
return parent.appendChild(el); | |
} | |
// вызов АPI метода - реализация GET запроса | |
fetch(url) | |
.then((resp) => resp.json()) // Параметр resp принимает значение объекта, возвращаемого fetch(url). Используйте метод json(), чтобы конвертировать resp в данные JSON | |
.then(function(data) { // обработка полученных данных | |
let authors = data.results; // переменная для результатов запроса | |
return authors.map(function(author) { // создаём элемент списка для каждого автора из результата запроса | |
let li = createNode('li'); | |
let img = createNode('img'); | |
let span = createNode('span'); | |
img.src = author.picture.medium; | |
span.innerHTML = `${author.name.first} ${author.name.last}`; | |
append(li, img); | |
append(li, span); | |
append(ul, li); | |
}) | |
}) | |
.catch(function(error) { | |
console.log(error); | |
}); | |
</script> | |
</body> | |
</html> | |
<!-- | |
https://www.digitalocean.com/community/tutorials/how-to-use-the-javascript-fetch-api-to-get-data-ru#2-fetch-api | |
--> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment