Sorğunu başlat və cavabı oxu
fetch(url) standart olaraq GET başlayır və Response üçün Promise qaytarır. response.json() gövdəni oxuyan ikinci asinxron addımdır. Sorğunun bitməsi ilə məlumatın emalı eyni mərhələ deyil. Aşağıdakı HTML-i saytın mənşəyində sınayanda lokal nümunə məlumatı yüklənir.
<button type="button" id="load">İstifadəçiləri göstər</button>
<p id="status" role="status"></p>
<ul id="users"></ul>
<script>
document.querySelector('#load').addEventListener('click', async () => {
const status = document.querySelector('#status');
const list = document.querySelector('#users');
status.textContent = 'Yüklənir…';
list.replaceChildren();
try {
const response = await fetch('/examples/frontend/users.json');
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const users = await response.json();
if (!Array.isArray(users)) throw new Error('Gözlənilməyən məlumat');
for (const user of users) {
const li = document.createElement('li');
li.textContent = user.name;
list.append(li);
}
status.textContent = users.length ? 'Hazırdır' : 'İstifadəçi tapılmadı';
} catch {
status.textContent = 'Məlumatı yükləmək alınmadı. Yenidən sına.';
}
});
</script>
HTTP xətası avtomatik rədd deyil
Fetch şəbəkə xətasında rədd edilə bilər, amma 404 və 500 üçün Response verə bilər. Buna görə ok yoxlaması vacibdir. Gövdə növünə görə json, text, blob kimi metod seç; eyni gövdəni təkrar oxumağa çalışma. İstifadəçi mətnini DOM-a textContent ilə yaz. Yolun users.json hissəsini dəyişərək xəta vəziyyətini yoxla.