📅  最后修改于: 2023-12-03 15:35:46.849000             🧑  作者: Mango
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.
To create a XHR object, we use the XMLHttpRequest()
constructor:
let xhr = new XMLHttpRequest();
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.
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.
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.