June 8, 2023
Certainly! XHR (XMLHttpRequest) is another way to make HTTP requests in JavaScript. It is an older API compared to the Fetch API but is still widely supported. Here's an example of how to use XHR to make a GET request:
1var xhr = new XMLHttpRequest();
2xhr.open('GET', 'https://api.example.com/data', true);
3
4xhr.onload = function() {
5 if (xhr.status >= 200 && xhr.status < 400) {
6 var data = JSON.parse(xhr.responseText);
7 console.log(data);
8 // Process the retrieved data here
9 } else {
10 console.error('Error:', xhr.status);
11 }
12};
13
14xhr.onerror = function() {
15 console.error('Request failed');
16};
17
18xhr.send();
19
In this example, we create a new instance of XMLHttpRequest
using the new XMLHttpRequest()
constructor. We then open a GET request by calling xhr.open('GET', url, async)
, where url
is the URL you want to request and async
is a boolean indicating whether the request should be asynchronous (true
by default).
Next, we define an onload
callback function that will be called when the request is completed. Inside the callback, we check if the request was successful by verifying the status code (xhr.status
). If it falls within the range of 200 to 399, we parse the response text using JSON.parse(xhr.responseText)
and process the retrieved data accordingly.
If the request encounters an error, the onerror
callback will be triggered, allowing you to handle the error appropriately.
Finally, we call xhr.send()
to send the request.
It's important to note that XHR has some limitations compared to the Fetch API. For example, it doesn't support promises natively, and handling complex request/response scenarios can be more cumbersome. The Fetch API provides a more modern and flexible way of working with HTTP requests in JavaScript.
No posts found in the category "Javascript"