📜  AJAX-XMLHttpRequest(1)

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

AJAX-XMLHttpRequest

AJAX (Asynchronous JavaScript and XML) is a technique used for creating fast and dynamic web pages. It allows to update a web page without reloading the whole page.

XMLHttpRequest is one of the core technologies behind AJAX. It enables client-side scripts to communicate with the server-side without reloading the page. It can send and receive data in various formats such as JSON, XML, HTML, and TEXT.

How it works

When an XMLHttpRequest is created, it can be used to open a connection to the server using the open() method. After that, we can set the method for the HTTP request (e.g. GET or POST) using the setRequestHeader() method. We can also set the content type of the request and other headers if necessary.

The send() method is used to send the request to the server. It can take a parameter that contains any data we want to send to the server. Once the server receives the request, it can process the data and send a response back to the client.

The onreadystatechange function is called every time the ready state of the XMLHttpRequest changes. We can use it to check the status of the request and handle the response. When the ready state is 4, the response from the server is ready to be processed. We can use the responseText property to get the content of the response in a string format.

Example
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
  if (xhr.readyState === 4 && xhr.status === 200) {
    console.log(xhr.responseText);
  }
};
xhr.open('GET', 'https://jsonplaceholder.typicode.com/todos/1');
xhr.send();

In this example, we create a new XMLHttpRequest object and set the onreadystatechange function to handle the response. We then use the open() method to open a connection to the server and set the HTTP method to GET. Finally, we use the send() method to send the request to the server.

When the ready state changes to 4 and the status is 200 (OK), we log the response to the console.

Conclusion

XMLHttpRequest is an essential part of AJAX and web development. It allows us to make HTTP requests and handle responses without the need to reload the whole page. With it, we can create fast and dynamic web pages that provide a better user experience.