Method fetch
2. Method fetch
Referensi:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
Dalam artikel ini, Anda akan mempelajari method fetch untuk mengirimkan
asynchronous HTTP request pada API selain XMLHttpRequest .
fetch(<URL>, <OPTIONS>)
.then(response => response.json())
.then(data => cons
ole.log(data));
Kita tidak perlu terlau dalam memahami perbedaan XMLHttpRequest dan fetch ,
intinya fetch seharusnya menjadi pilihan pertama, mari kita gantikan code
XMLHttpRequest sebelumnya dengan fetch .
https://www.notion.so/2-Method-fetch-af034d00c25845a0901eeba82272056a 1/2
6/21/22, 9:09 PM 2. Method fetch
function fetchData() {
const xhttp = new XMLHttpRequest();
const url = "http
s://pokeapi.co/api/v2/pokemon?limit=10";
const httpMethod = "GET";
xhttp.onlo
ad = function() {
const response = JSON.parse(this.responseText);
const resul
ts = response.results;
let data = ''
for (i = 0; i < results.length; i++) {
d
ata = data + `<p>${results[i].name}</p>`;
}
document.getElementById("progate"
).innerHTML = data;
}
xhttp.open(httpMethod, url);
xhttp.send();
}
https://www.notion.so/2-Method-fetch-af034d00c25845a0901eeba82272056a 2/2