JAVASCRIPT Tutorial
The XMLHttpRequest (XHR) object is a fundamental tool for web development, enabling asynchronous data transfer between a web page and a server. It plays a crucial role in AJAX (Asynchronous JavaScript and XML), a technique used to create dynamic and interactive web applications.
let xhr = new XMLHttpRequest();
xhr.open("GET", "data.txt");
xhr.send();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
console.log(xhr.responseText);
} else {
console.error("Error: " + xhr.status);
}
}
};
The following JavaScript code demonstrates the use of the XMLHttpRequest object:
const xhr = new XMLHttpRequest();
xhr.open("GET", "data.txt");
xhr.send();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
document.getElementById("response").innerHTML = xhr.responseText;
} else {
console.error("Error: " + xhr.status);
}
}
};
This code creates an XMLHttpRequest object, sends a GET request to a text file, and displays the response in an HTML element with the ID "response".
The XMLHttpRequest object is a powerful tool for data exchange between web pages and servers. It enables the creation of dynamic and interactive applications without requiring full page reloads. Understanding the concepts and practical steps outlined in this guide will empower developers to effectively utilize XHR in their web development projects.