Skip to content

Instantly share code, notes, and snippets.

@ShilGen
Last active September 21, 2023 16:26
Show Gist options
  • Save ShilGen/ba1b878bf3c940244a85baea9e79456e to your computer and use it in GitHub Desktop.
Save ShilGen/ba1b878bf3c940244a85baea9e79456e to your computer and use it in GitHub Desktop.
JS Fetch GET example
<!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