Using XMLHttpRequest and Fetch API for Ajax Requests
๐ Ajax Interfaces: XMLHttpRequest vs. Fetch API
Modern web development primarily utilizes two interfaces for Ajax requests: XMLHttpRequest
and the Fetch API
.
๐งพ XMLHttpRequest
var xhr = new XMLHttpRequest();
xhr.open('GET', 'data.json', true);
xhr.onload = function() {
if (xhr.status === 200) {
var data = JSON.parse(xhr.responseText);
console.log(data);
}
};
xhr.send();
๐งผ Fetch API
fetch('data.json')
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => console.error('Error:', error));
๐ While XMLHttpRequest
has been the traditional choice, the Fetch API
offers a cleaner, promise-based syntax, making code easier to write and maintain.
๐ Developers should prefer Fetch
for new projects, but XMLHttpRequest
remains relevant for legacy browser support.