Skip to content

Instantly share code, notes, and snippets.

@sunmeat
Created May 4, 2025 15:47
Show Gist options
  • Save sunmeat/ad4c1132cee2e67ed5224609214bfb2b to your computer and use it in GitHub Desktop.
Save sunmeat/ad4c1132cee2e67ed5224609214bfb2b to your computer and use it in GitHub Desktop.
GET XmlHttpRequest example
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="UTF-8">
<title>Пример гет-запроса с помощью XMLHttpRequest</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #121212;
color: #ffffff;
text-align: center;
padding: 2rem;
}
input, button {
padding: 0.5rem;
margin: 0.5rem;
border-radius: 5px;
border: none;
}
button {
background-color: #1db954;
color: #ffffff;
cursor: pointer;
}
button:hover {
background-color: #1ed760;
}
.image-result {
margin: 1rem 0;
}
img {
max-width: 100%;
height: auto;
border-radius: 10px;
margin-top: 1rem;
}
select {
padding: 0.5rem;
border-radius: 5px;
margin: 0.5rem;
}
</style>
</head>
<body>
<h1>Поиск изображений на Pixabay (XMLHttpRequest)</h1>
<input type="text" id="query" placeholder="Введите запрос (например, 'nature')" value="nature" size="70">
<select id="imageType">
<option value="photo">Фото</option>
<option value="illustration">Иллюстрация</option>
<option value="vector">Вектор</option>
</select>
<br>
<button onclick="searchImages()">Найти изображения</button>
<div id="results"></div>
<script>
const apiKey = '50059311-67b92461e0c6542f48deaee0e'; // если не работает, получите свой апи-ключ :)
function searchImages() {
const query = document.getElementById('query').value;
const imageType = document.getElementById('imageType').value;
const resultsDiv = document.getElementById('results');
resultsDiv.innerHTML = '<p>Поиск...</p>';
// создание GET-запроса с двумя параметрами
const xhr = new XMLHttpRequest();
const url = `https://pixabay.com/api/?key=${apiKey}&q=${encodeURIComponent(query)}&image_type=${imageType}&per_page=5`;
xhr.open('GET', url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
const data = JSON.parse(xhr.responseText);
if (data.hits && data.hits.length > 0) {
resultsDiv.innerHTML = '';
data.hits.forEach(image => displayImage(image, resultsDiv));
} else {
resultsDiv.innerHTML = '<p>Изображения не найдены</p>';
}
} else {
resultsDiv.innerHTML = `<p>Ошибка: ${xhr.status} ${xhr.statusText}</p>`;
}
}
};
xhr.onerror = function() {
resultsDiv.innerHTML = '<p>Ошибка сети</p>';
};
xhr.send();
}
function displayImage(image, container) {
const div = document.createElement('div');
div.className = 'image-result';
div.innerHTML = `
<p><strong>${image.user}</strong> (Теги: ${image.tags})</p>
<img src="${image.webformatURL}" alt="${image.tags}">
`;
container.appendChild(div);
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment