Fetch API and AJAX
Expert-Level Explanation
Fetch API and AJAX (asynchronous JavaScript and XML) are used for handling asynchronous HTTP requests in JavaScript. Fetch API, a modern approach introduced in ES6, uses Promises to handle responses and provides a more powerful and flexible feature set compared to AJAX. AJAX, traditionally utilising the XMLHttpRequest
object, allows for asynchronous requests to a server without refreshing the webpage.
Creative Explanation
Think of the Fetch API and AJAX as tools for sending letters (requests) and receiving responses. Fetch API is like using email with advanced features like read receipts (promises), while AJAX is like traditional mail using postcards (XMLHttpRequest
).
Practical Explanation with Code
// Using Fetch API
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
// Using AJAX
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(JSON.parse(xhr.responseText));
}
};
xhr.open("GET", "https://api.example.com/data", true);
xhr.send();
Real-world Example
Imagine ordering food online. Fetch API is like using a modern app where you track your order in real-time, while AJAX is like making a phone call and checking periodically if your order is ready.