JavaScript HTTP 请求:XMLHttpRequest 与 Fetch API 详解
使用 JavaScript 发出 HTTP 请求可以通过内置的 XMLHttpRequest 对象或使用现代的 fetch API 来实现。以下是两种方法的示例:
使用 XMLHttpRequest 对象:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com/api', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var response = xhr.responseText;
console.log(response);
}
};
xhr.send();
使用 fetch API:
fetch('https://example.com/api')
.then(function(response) {
if (response.ok) {
return response.text();
}
throw new Error('Network response was not ok.');
})
.then(function(responseText) {
console.log(responseText);
})
.catch(function(error) {
console.log('Error:', error.message);
});
这两种方法都可以用于发送 GET 请求。如果要发送 POST 请求或其他类型的请求,可以根据需要设置请求头和请求体。请注意,fetch API 是现代浏览器中的标准方法,而 XMLHttpRequest 对象与更旧的浏览器兼容性更好。
原文地址: https://www.cveoy.top/t/topic/bxYc 著作权归作者所有。请勿转载和采集!