спиннер загрузки с сервера

This commit is contained in:
2025-12-14 00:01:54 +03:00
parent a9e57b4a38
commit a3c48b55a1
3 changed files with 67 additions and 8 deletions
+31 -8
View File
@@ -1,4 +1,23 @@
// api.js
let loaderTimeout = null;
function showLoader() {
const loader = document.getElementById('globalLoader');
if (!loader) return;
clearTimeout(loaderTimeout);
loader.classList.remove('d-none');
}
function hideLoader() {
const loader = document.getElementById('globalLoader');
if (!loader) return;
loaderTimeout = setTimeout(() => {
loader.classList.add('d-none');
}, 200); // задержка 0.2 сек
}
export async function apiRequest(url, payload = {}, method = 'POST') {
method = method.toUpperCase();
@@ -12,21 +31,25 @@ export async function apiRequest(url, payload = {}, method = 'POST') {
credentials: 'same-origin'
};
// --- Если GET → добавляем payload в URL ---
if (method === 'GET') {
const params = new URLSearchParams(payload);
finalUrl = `${url}?${params.toString()}`;
} else {
// --- Для остальных методов → отправляем body ---
options.body = JSON.stringify(payload);
}
const res = await fetch(finalUrl, options);
showLoader();
if (!res.ok) {
const text = await res.text();
throw new Error(`HTTP ${res.status}: ${text}`);
try {
const res = await fetch(finalUrl, options);
if (!res.ok) {
const text = await res.text();
throw new Error(`HTTP ${res.status}: ${text}`);
}
return await res.json();
} finally {
hideLoader();
}
return res.json();
}