API & Fetch — ดึงข้อมูลจาก API สาธารณะ

ในบทนี้เราจะใช้งาน fetch เพื่อดึงข้อมูลจาก API สาธารณะ (เช่น JSONPlaceholder) และแสดงผลบนหน้าเว็บด้วย async/await

ตัวอย่าง (fetch)


<ul id="posts"></ul>
<script>
async function loadPosts(){
    try {
        const res = await fetch('https://jsonplaceholder.typicode.com/posts?_limit=6');
        const posts = await res.json();
        const list = document.getElementById('posts');
        list.innerHTML = posts.map(p => `<li><strong>${p.title}</strong><p>${p.body}</p></li>`).join('');
    } catch (e) {
        console.error(e);
    }
}

loadPosts();
</script>