fetch('https://api.example.com/products') // แทนที่ด้วย URL ของ API จริง
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok ' + response.statusText);
}
return response.json(); // แปลง Response เป็น JSON
})
.then(data => {
console.log(data); // แสดงผลข้อมูลที่ได้จาก API ใน Console
// ตัวอย่างการนำข้อมูลไปแสดงผลบนหน้าเว็บ
const productList = document.getElementById('product-list');
data.forEach(product => {
const li = document.createElement('li');
li.textContent = `ID: ${product.id}, Name: ${product.name}, Price: ${product.price}`;
productList.appendChild(li);
});
})
.catch(error => {
console.error('There was a problem with the fetch operation:', error);
});