/
thugger
/
hhh
Обзор
Документация
Войти
/
thugger
/
hhh
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
r2.html
140 строк
5 KB
thugger
create: r2.html
15 май 2026, 16:33
Верифицирован
15 май 2026, 16:33
efaf6c0
Код
Авторство
О чём код?
<!DOCTYPE html> <html lang="ru"> <head> <meta charset="UTF-8"> <title>Дифф. зачёт ОАИП - Полная работа</title> <style> :root { --bg: #0f172a; --card: #1e293b; --accent: #38bdf8; --text: #f1f5f9; } body { font-family: 'Segoe UI', Tahoma, sans-serif; background: var(--bg); color: var(--text); padding: 20px; } .wrapper { max-width: 900px; margin: 0 auto; } /* Стили формы */ .section { background: var(--card); padding: 25px; border-radius: 12px; margin-bottom: 30px; border: 1px solid #334155; } .input-box { margin-bottom: 15px; } input, textarea { width: 100%; padding: 12px; background: #0f172a; border: 1px solid #475569; color: white; border-radius: 6px; box-sizing: border-box; } button { background: var(--accent); color: #0f172a; border: none; padding: 12px 25px; border-radius: 6px; font-weight: bold; cursor: pointer; } button:disabled { opacity: 0.5; cursor: not-allowed; } /* Стили сетки постов */ .post-list { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 20px; } .post-item { background: var(--card); padding: 15px; border-radius: 8px; border-left: 4px solid var(--accent); transition: 0.3s; } .post-item:hover { transform: scale(1.02); } .error-log { color: #f87171; background: #450a0a; padding: 10px; border-radius: 6px; margin-bottom: 10px; display: none; } </style> </head> <body> <div class="wrapper"> <div class="section"> <h2>1 & 2. Создание и отображение постов</h2> <div id="error-display" class="error-log"></div> <form id="postForm"> <div class="input-box"><input type="text" id="postTitle" placeholder="Заголовок" required></div> <div class="input-box"><textarea id="postBody" placeholder="Текст поста" required></textarea></div> <button type="submit" id="submitBtn">Опубликовать (Rate Limited)</button> </form> </div> <div class="section"> <h2>Лента сообщений</h2> <div id="postsContainer" class="post-list"></div> </div> </div> <script> // --- ЗАДАНИЕ 2: Rate Limiter (Алгоритм скользящего окна) --- let requestHistory = []; const WINDOW_SIZE = 5000; // 5 секунд const MAX_REQUESTS = 3; // Макс. 3 запроса function checkRateLimit() { const now = Date.now(); requestHistory.push(now); // Реализация скользящего окна (Two Pointers logic) let left = 0; while (now - requestHistory[left] > WINDOW_SIZE) { left++; } // Очищаем историю от старых записей requestHistory = requestHistory.slice(left); return requestHistory.length > MAX_REQUESTS; } // --- ЗАДАНИЕ 1: Работа с сетью (fetch + try-catch) --- const API = 'https://jsonplaceholder.typicode.com/posts'; // Функция загрузки постов async function loadPosts() { const container = document.getElementById('postsContainer'); try { const response = await fetch(`${API}?_limit=6`); if (!response.ok) throw new Error('Ошибка при получении данных'); const posts = await response.json(); container.innerHTML = posts.map(p => ` <div class="post-item"> <h4>${p.title}</h4> <p>${p.body.substring(0, 80)}...</p> </div> `).join(''); } catch (err) { showError(`Не удалось загрузить ленту: ${err.message}`); } } // Функция отправки формы async function handleForm(e) { e.preventDefault(); const errorDisplay = document.getElementById('error-display'); errorDisplay.style.display = 'none'; // Применяем Rate Limiter if (checkRateLimit()) { showError("Слишком часто! Лимит: 3 запроса за 5 сек."); return; } const data = { title: document.getElementById('postTitle').value, body: document.getElementById('postBody').value, userId: 1 }; try { const response = await fetch(API, { method: 'POST', body: JSON.stringify(data), headers: { 'Content-type': 'application/json' } }); if (!response.ok) throw new Error('Ошибка сервера при сохранении'); const result = await response.json(); alert(`Успех! Пост создан (ID: ${result.id})`); document.getElementById('postForm').reset(); } catch (err) { showError(`Ошибка отправки: ${err.message}`); } } function showError(msg) { const errDiv = document.getElementById('error-display'); errDiv.textContent = msg; errDiv.style.display = 'block'; } // Старт document.getElementById('postForm').addEventListener('submit', handleForm); loadPosts(); </script> </body> </html>