
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://rg0.net/api/data');
xhr.onload = function() {
if (xhr.status === 200) {
console.log(xhr.responseText);
}
};
xhr.send();
Bu kod, http://rg0.net/api/data adresine bir GET isteği yapar ve cevabı alır. Cevap, xhr.responseText özelliğiyle elde edilebilir.
Başka bir yöntem de, fetch() işlevini kullanmaktır. Bu işlev, tarayıcının built-in bir HTTP istekleri çalıştırma mekanizmasıdır ve XMLHttpRequest'in yerine kullanılabilir. Örneğin, aşağıdaki kod aynı GET isteğini yapar:fetch('http://rg0.net/api/data')
.then(response => response.text())
.then(text => console.log(text));
Bu kod, http://rg0.net/api/data adresine bir GET isteği yapar ve cevabı alır. Cevap, response.text() ile elde edilebilir ve daha sonra console.log() ile yazdırılabilir.
Her iki yöntem de tarayıcıda çalışır ve kullanılabilir olduğu sürece çalışır. Ancak, XMLHttpRequest nesnesi daha eski bir API'dir ve fetch() daha modern bir yöntemdir.
Not: Bu yöntemler sadece tarayıcıda çalışır. Sunucu tarafında (örneğin, Node.js) HTTP istekleri yapmak için başka yöntemler kullanılır.
Tags:
JavaScript