Once a request is sent, the server processes it and sends back data. The XMLHttpRequest object provides several properties to access this response data and metadata like headers.
Click the button below to fetch a file and inspect the HTTP Response Headers sent back by the server:
The two main properties used to retrieve data from the server are:
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
The onreadystatechange property defines a function to be executed every time
the status of the XMLHttpRequest object changes.
readyState 4).
Before processing data, you should always check the HTTP status code:
Headers provide extra information about the server response, such as content type, date, or server software.
Returns all the header information as a single string.
let headers = xhttp.getAllResponseHeaders();
Returns a specific piece of header information.
let contentType = xhttp.getResponseHeader("Content-type");