Computers & ProgrammingAJAXFrontend Development

Retrieving Header Information with AJAX

The XMLHttpRequest object includes two methods that allow you to retrieve either all of the response header information or certain fields within the response header. The two methods are getAllResponseHeaders and getResponseHeader. In this tutorial, we will take a closer look at both methods.

Example

We will use the following HTML for the examples listed below.

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript">
        callFunction(){
            // ... JavaScript code
        }
    </script>
</head>
<body>
    <img id="img1" onclick="callFunction()" src="go.png" /> ; 
    <div id="div1"> <!-- Some Content --> </div>
</body>
</html>

Syntax

xhr.getAllResponseHeaders();
xhr.getResponseHeader(header);

If you are interested in retrieving all response headers, use the getAllResponseHeaders() method. If you only need access to a particular header, use the getResponseHeader(header) method and replace the ‘header’ variable with the name of the header you are interested in retrieving. Here are some examples:

XMLHTTPRequest Response Header Methods

MethodDescription
getAllResponseHeaders()Returns header information
getResponseHeader(header)Returns specific header information

getAllResponseHeaders()

xhr.onreadystatechange = function () {
    if (xhr.readyState == 4 && xhr.status == 200) {
        document.getElementById("div1").innerHTML = xhr.getAllResponseHeaders();
    }
}

getResponseHeader(header)

xhr.onreadystatechange = function () {
    if (xhr.readyState == 4 && xhr.status == 200) {
        document.getElementById("div1").innerHTML = xhr.getResponseHeader('Response');
    }
}

Leave a Comment

Your email address will not be published.

Scroll to Top