10 a] Describe the role of XHTML HttpRequest and Response in AJAX.
In AJAX (Asynchronous JavaScript and XML), XMLHttpRequest
and Response
play crucial roles in enabling asynchronous communication between the client and the server without requiring a full page reload. Here’s a breakdown of their roles:
1. XMLHttpRequest
(XHR)
XMLHttpRequest
is an API provided by browsers to interact with servers asynchronously. It allows web pages to request data from a server and update parts of the page without reloading the entire page. Here’s how it works:
- Creating an Instance: You create an instance of
XMLHttpRequest
to handle the communication.var xhr = new XMLHttpRequest();
- Configuring the Request: You configure the request by specifying the HTTP method (GET, POST, etc.) and the URL to which the request should be sent.
xhr.open('GET', 'https://api.example.com/data', true);
- Sending the Request: You send the request to the server. For GET requests, this is usually done without any additional data. For POST requests, you might include data in the request body.
xhr.send();
- Handling the Response: You define a callback function that handles the server’s response. This function is triggered when the request completes.
xhr.onreadystatechange = function() { if (xhr.readyState === XMLHttpRequest.DONE) { if (xhr.status === 200) { console.log(xhr.responseText); } else { console.error('Request failed with status ' + xhr.status); } } };
xhr.readyState
: Represents the state of the request (e.g., loading, done).xhr.status
: Represents the HTTP status code of the response (e.g., 200 for success).xhr.responseText
: Contains the response data in text form.
2.Response
Object
The Response
object is a modern JavaScript interface used in the Fetch API, which is an alternative to XMLHttpRequest
for making HTTP requests. It provides a more powerful and flexible way to handle responses. Key properties and methods include:
- Handling the Response: The
Response
object contains several properties and methods to handle different types of response data.fetch('https://api.example.com/data') .then(response => { if (!response.ok) { throw new Error('Network response was not ok'); } return response.json(); // Parse JSON data }) .then(data => { console.log(data); }) .catch(error => { console.error('There has been a problem with your fetch operation:', error); });
- Key Methods and Properties:
response.ok
: A boolean indicating whether the response was successful (status in the range 200-299).response.json()
: Parses the response body as JSON.response.text()
: Parses the response body as plain text.response.blob()
: Parses the response body as a binary large object (Blob).response.headers
: Provides access to the response headers.