📜  XHR - Javascript (1)

📅  最后修改于: 2023-12-03 15:35:46.849000             🧑  作者: Mango

XHR - Javascript

XHR, or XMLHttpRequest, is a Javascript object that allows for asynchronous communication between client-side scripts and servers, allowing for updating a web page without reloading the page.

How to create a XHR object

To create a XHR object, we use the XMLHttpRequest() constructor:

let xhr = new XMLHttpRequest();
How to make a request

After creating a XHR object, we can use it to make a request to a server using the open() and send() methods:

xhr.open('GET', 'http://example.com/data.json', true);
xhr.send();

This example sends a GET request to http://example.com/data.json, with the true parameter indicating that the request should be asynchronous.

How to handle response

We can handle the response by setting an event listener for the readystatechange event:

xhr.addEventListener('readystatechange', function() {
  if (xhr.readyState === XMLHttpRequest.DONE) {
    console.log(xhr.responseText);
  }
});

This example logs the response text to the console when the request is completed. The readystatechange event fires when the readyState property changes, which can occur multiple times before the request is completed.

Conclusion

XHR is a powerful tool for making asynchronous requests to servers and updating content on a web page without reloading the page. By understanding its basic usage and response handling, we can utilize XHR to enhance user experience and interaction on a website.