Using XMLHttpRequest:
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.example.com/data", true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var response = JSON.parse(xhr.responseText);
console.log(response);
}
};
xhr.send();
Using fetch:
fetch("https://api.example.com/data")
.then(function (response) {
if (response.ok) {
return response.json();
} else {
throw new Error("HTTP status code: " + response.status);
}
})
.then(function (data) {
console.log(data);
})
.catch(function (error) {
console.log(error);
});
In both examples, we are making a GET request to "https://api.example.com/data"
. You can replace it with the URL you want to fetch. The response from the server is handled in a callback function that parses the response as JSON and logs it to the console.
Note that the fetch API returns a promise, allowing you to use the chaining syntax with then
and catch
for handling success and error scenarios.
Choose the approach that suits your needs and browser compatibility requirements. The fetch API is more modern and has better support for promises, but the XMLHttpRequest object is still widely used and supported.