Introduction
- You may use the built-in XMLHttpRequest object or the more recent get() function to send an HTTP request in Javascript.
Here are examples of how to use each :
Using XMLHttpRequest
// create a new XMLHttpRequest object const xhr = new XMLHttpRequest(); // define the HTTP method, URL, and async flag xhr.open('GET', 'https://example.com/data.json', true); // set any headers (optional) xhr.setRequestHeader('Content-Type', 'application/json'); // define a callback function to handle the response xhr.onload = function() { if (xhr.status === 200) { console.log(xhr.responseText); } else { console.error('Request failed. Returned status of ' + xhr.status); } }; // send the request xhr.send();