JavaScript HTTP 请求: XMLHttpRequest vs. Fetch API
要使用 JavaScript 发出 HTTP 请求,你可以使用内置的 XMLHttpRequest 对象或者更现代的 fetch API。以下是两种方法的示例:
使用 XMLHttpRequest 对象:
var xhr = new XMLHttpRequest();
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();
使用 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(data) {
console.log(data);
})
.catch(function(error) {
console.log('Error:', error.message);
});
这些代码示例分别使用了 XMLHttpRequest 和 fetch API 发送 GET 请求。你可以将请求地址替换为你要访问的 API 的 URL,并根据需要调整代码以发送其他类型的请求(例如 POST 请求)或添加请求头等。
原文地址: https://www.cveoy.top/t/topic/bQ0p 著作权归作者所有。请勿转载和采集!