In JavaScriptXMLHttpRequest
objectfetch
API
Using XMLHttpRequest
:
var xhr = new XMLHttpRequest();
xhr.
xhr
open('GET', 'https://api.example.com/data', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var response = JSON.parse(xhr.responseText);
console.log(response);
}
};
xhr.send();
In this example, we create a new XMLHttpRequest
object, set the request method and URL using the open
method, define a callback function for the onreadystatechange
event, and finally send the request using the send
method. The callback function is called whenever the readyState
changes, and we check if the request is complete (readyState === 4
) and the status is successful (status === 200
) before parsing and logging the response.
Using fetch
:
fetch('https://api.example.com/data')
.then(function(response) {
if (response.ok) {
return response.json();
}
throw new Error('Network response was not ok.');
})
.then(function(data) {
console.log(data);
})
.catch(function(error) {
console.log('Error:', error.message);
});
In this example, we use the fetch
function to make a GET request to the specified URL. The response is returned as a Promise, which allows us to chain .then
and .catch
methods. In the first .then
block, we check if the response was successful (response.ok
) and parse the JSON response using the json
method. If the response was not successful, an error is thrown. In the second .then
block, we log the parsed data. Finally, any errors are caught in the .catch
block and logged.
Both methods can be used to make different types of requests (GET, POST, PUT, DELETE, etc.) by specifying the appropriate method in the open
method for XMLHttpRequest
, or by passing an options object to the fetch
function.
Note that the fetch
API is more modern and provides a more flexible and convenient way of making HTTP requests, but XMLHttpRequest
is still widely supported and can be used in older browsers or in specific situations where needed.