Intro to JavaScript XHR
JavaScript's XMLHttpRequest (XHR) object allows developers to make HTTP requests from a web page. This can be used to retrieve data from a server without having to refresh the entire page. In this article, we will go over how to make XHR requests in JavaScript.
First, we need to create an instance of the XHR object. This can be done using the following code:
var xhr = new XMLHttpRequest();
Next, we need to open a connection to the server using the open()
method of the XHR object. This method takes three arguments: the HTTP method (such as "GET" or "POST"), the URL of the server, and a Boolean indicating whether the request should be asynchronous (true
) or synchronous (false
).
xhr.open("GET", "http://example.com", true);
Once the connection is open, we can send the request to the server using the send()
method. This method takes one optional argument, which is the data to be sent with the request. For example, if we are sending a POST request with some data, we would use the following code:
xhr.send("name=value");
To handle the response from the server, we need to set an event listener for the onreadystatechange
event of the XHR object. This event is triggered every time the readyState property of the XHR object changes. The readyState property is a numeric value that indicates the current state of the request. A value of 4 indicates that the request is complete, and the response is available.
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
console.log(xhr.responseText);
}
};
In this example, we are using the console.log()
function to print the response from the server to the console. However, you could also parse the response as JSON, or use it to update the contents of the web page.
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
var response = JSON.parse(xhr.responseText);
console.log(response);
}
};
It's worth noting that XHR has been replaced by the Fetch API in modern browsers, and the fetch API is more powerful and easier to use.
fetch("http://example.com")
.then(response => response.text())
.then(data => {
console.log(data);
});
In summary, making XHR requests in JavaScript is relatively simple. By creating an instance of the XHR object, opening a connection to the server, and setting an event listener for the onreadystatechange
event, you can retrieve data from a server and update the contents of a web page without refreshing the entire page.