Created
May 5, 2025 08:33
-
-
Save sunmeat/00469aff226e7ef972b0c6cadf8089ec to your computer and use it in GitHub Desktop.
концепт AJAX
This file contains hidden or 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=""> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Концепт AJAX</title> | |
<style> | |
body { | |
font-family: Arial, sans-serif; | |
background-color: #121212; | |
color: #ffffff; | |
padding: 2rem; | |
margin: 0; | |
text-align: center; | |
} | |
.container { | |
max-width: 600px; | |
margin: 0 auto; | |
background-color: #1e1e1e; | |
padding: 20px; | |
border-radius: 10px; | |
} | |
button { | |
padding: 0.5rem 1rem; | |
margin: 10px; | |
border-radius: 5px; | |
border: none; | |
background-color: #1db954; | |
color: #ffffff; | |
cursor: pointer; | |
font-size: 16px; | |
} | |
button:hover { | |
background-color: #1ed760; | |
} | |
.joke-box { | |
margin: 20px 0; | |
padding: 10px; | |
border: 1px solid #444; | |
border-radius: 5px; | |
text-align: left; | |
white-space: pre-wrap; | |
} | |
.error { | |
color: #FF5555; | |
margin: 10px 0; | |
} | |
</style> | |
</head> | |
<body> | |
<div class="container"> | |
<h2>AJAX на Fetch API</h2> | |
<button onclick="fetchJoke()">Получить случайную шутку</button> | |
<div id="result"></div> | |
</div> | |
<script> | |
const apiUrl = 'https://v2.jokeapi.dev/joke/Programming'; | |
const resultDiv = document.querySelector('#result'); | |
async function fetchJoke() { | |
resultDiv.innerHTML = '<p>Загрузка...</p>'; | |
try { | |
// отправка асинхронного GET-запроса с помощью Fetch API | |
const response = await fetch(apiUrl, { | |
method: 'GET', | |
headers: { | |
'Accept': 'application/json' | |
} | |
}); | |
if (!response.ok) { | |
throw new Error(`HTTP ошибка: ${response.status}`); | |
} | |
const data = await response.json(); | |
const jokeText = data.type === 'single' | |
? data.joke | |
: `${data.setup}\n${data.delivery}`; | |
// !!! обновление DOM без перезагрузки страницы !!! | |
resultDiv.innerHTML = ` | |
<div class="joke-box">${jokeText}</div> | |
`; | |
} catch (error) { | |
resultDiv.innerHTML = `<p class="error">Ошибка: ${error.message}</p>`; | |
} | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment