HTTP Requests in JavaScript: XMLHttpRequest & Fetch API
You can make an HTTP request in JavaScript using the built-in 'XMLHttpRequest' object or the newer 'fetch()' API. Here's an example of each:
Using XMLHttpRequest:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com/api/data', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
};
xhr.send();
Using fetch():
fetch('https://example.com/api/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
Both of these examples make a GET request to 'https://example.com/api/data'. The XMLHttpRequest example sets up an event listener to handle the response, while the fetch() example uses promises to handle the response.
原文地址: https://www.cveoy.top/t/topic/mBz1 著作权归作者所有。请勿转载和采集!