To make an HTTP GET request to fetch data from a remote server using JavaScript, you can use the XMLHttpRequest or the newer Fetch API. Here are examples using both methods:
Using XMLHttpRequest:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);
xhr.onload = function() {
if (xhr.status === 200) {
var responseData = JSON.parse(xhr.responseText);
// Process the responseData as needed
}
};
xhr.send();
Using Fetch API:
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(responseData) {
// Process the responseData as needed
})
.catch(function(error) {
// Handle any error that occurred during the request
});
Note that in both examples, you need to replace 'https://api.example.com/data'
with the actual URL from which you want to fetch data. Additionally, you may need to handle any errors that occur during the request, update the code to handle the fetched data appropriately, and adapt the response format if needed.