JavaScript 发出 HTTP 请求:XMLHttpRequest 与 Fetch API
使用 JavaScript 发出 HTTP 请求可以使用内置的 XMLHttpRequest 对象或现代的 fetch API。以下是一个示例,展示如何使用这两种方法之一发出 GET 请求:
使用 XMLHttpRequest 对象:
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
const response = JSON.parse(xhr.responseText);
console.log(response);
}
};
xhr.send();
使用 fetch API:
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log(error));
这两种方法都可以根据需要进行配置,例如添加请求头、发送 POST 请求等。根据你的具体要求,你可以进一步调整这些代码。
原文地址: https://www.cveoy.top/t/topic/TZ1 著作权归作者所有。请勿转载和采集!