Skip to content

Instantly share code, notes, and snippets.

@sunmeat
Created May 4, 2025 17:03
Show Gist options
  • Save sunmeat/5fed9819c40af1834f46755d79a6bf09 to your computer and use it in GitHub Desktop.
Save sunmeat/5fed9819c40af1834f46755d79a6bf09 to your computer and use it in GitHub Desktop.
отправка данных формы методом POST XMLHttpRequest
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="UTF-8">
<title>Отправка данных формы</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #121212;
color: #ffffff;
text-align: center;
padding: 2rem;
}
.container {
max-width: 600px;
margin: 0 auto;
background-color: #1e1e1e;
padding: 20px;
border-radius: 10px;
}
form {
display: flex;
flex-direction: column;
gap: 15px;
}
label {
font-weight: bold;
text-align: left;
}
input, select, textarea {
padding: 8px;
border-radius: 5px;
border: none;
background-color: #2a2a2a;
color: #ffffff;
width: 100%;
box-sizing: border-box;
}
input[type="file"] {
padding: 8px 0;
}
textarea {
resize: vertical;
min-height: 80px;
}
button {
padding: 0.5rem 1rem;
margin-top: 10px;
border-radius: 5px;
border: none;
background-color: #1db954;
color: #ffffff;
cursor: pointer;
}
button:hover {
background-color: #1ed760;
}
pre {
background-color: #2a2a2a;
padding: 10px;
border-radius: 5px;
white-space: pre-wrap;
word-wrap: break-word;
text-align: left;
}
.error {
color: #ff5555;
}
</style>
</head>
<body>
<div class="container">
<h2>Добавить питомца в магазин</h2>
<form id="petForm">
<label for="name">Имя питомца:</label>
<input type="text" id="name" name="name" required placeholder="Например, Барсик">
<label for="status">Статус:</label>
<select id="status" name="status" required>
<option value="available">Доступен</option>
<option value="pending">В ожидании</option>
<option value="sold">Продан</option>
</select>
<label for="category">Категория:</label>
<input type="text" id="category" name="category" placeholder="Например, Dog">
<label for="photos">Фотографии питомца:</label>
<input type="file" id="photos" name="photos" multiple accept="image/*">
<label for="tags">Теги (через запятую):</label>
<textarea id="tags" name="tags" placeholder="Например, дружелюбный, игривый"></textarea>
<button type="submit">Добавить питомца</button>
</form>
<div id="formResult"></div>
</div>
<script>
let form = document.querySelector('#petForm');
form.addEventListener('submit', function(e) {
e.preventDefault();
let xhr = new XMLHttpRequest();
xhr.open('POST', 'https://petstore.swagger.io/v2/pet', true);
xhr.setRequestHeader('Content-Type', 'application/json');
// собираем данные из формы
const name = form.querySelector('#name').value;
const status = form.querySelector('#status').value;
const category = form.querySelector('#category').value;
const photos = form.querySelector('#photos').files;
const tags = form.querySelector('#tags').value.split(',').map(tag => tag.trim()).filter(tag => tag).map(tag => ({ name: tag }));
// преобразуем загруженные файлы в локальные URL
const photoUrls = Array.from(photos).map(file => URL.createObjectURL(file));
// формируем JSON-объект
const data = {
name: name,
status: status,
category: category ? { name: category } : {},
photoUrls: photoUrls.length > 0 ? photoUrls : [],
tags: tags.length > 0 ? tags : []
};
xhr.onreadystatechange = function() {
const resultDiv = document.querySelector('#formResult');
if (xhr.readyState === 4) {
if (xhr.status === 200) {
const response = JSON.parse(xhr.responseText);
const formattedResponse = JSON.stringify(response, null, 2);
resultDiv.innerHTML = `
<p>Питомец успешно добавлен:</p>
<pre>${formattedResponse}</pre>
`;
// ссвобождаем локальные URL после отправки
photoUrls.forEach(url => URL.revokeObjectURL(url));
} else {
resultDiv.innerHTML = `<p class="error">Ошибка: ${xhr.status} ${xhr.statusText}</p>`;
}
} else {
resultDiv.innerHTML = '<p>Отправка...</p>';
}
};
xhr.onerror = function() {
document.querySelector('#formResult').innerHTML = '<p class="error">Ошибка сети.</p>';
};
xhr.send(JSON.stringify(data));
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment