The XMLHttpRequest API provides a way to create XMLHttpRequest objects, which allow you to send HTTP requests asynchronously from JavaScript.
This API allows you to make AJAX (Asynchronous JavaScript and XML) requests to servers without having to re-load the entire page. You can use this API to perform actions such as:
const xhr = new XMLHttpRequest();
xhr.open('GET', '/data');
xhr.onreadystatechange = function () {
if (xhr.status === 200) {
console.log(xhr.responseText);
}
};
xhr.send();
This example demonstrates how to create an XMLHttpRequest object, open a request, and handle the response.
const xhr = new XMLHttpRequest();
xhr.open('GET', '/data');
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
};
xhr.send();
const xhr = new XMLHttpRequest();
xhr.open('POST', '/data');
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
};
xhr.send(JSON.stringify({ key: 'value' }));