JavaScript HTTP 请求:XMLHttpRequest 和 Fetch 的用法
要使用 JavaScript 发出 HTTP 请求,您可以使用内置的 'XMLHttpRequest' 对象或使用现代的 'fetch' 函数。以下是使用两种方法之一发出 GET 请求的示例代码:
使用 XMLHttpRequest:
// 创建一个新的 XMLHttpRequest 对象
var xhr = new XMLHttpRequest();
// 设置请求的类型和 URL
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:
// 发出 GET 请求并处理响应
fetch('https://api.example.com/data')
.then(function(response) {
return response.json();
})
.then(function(data) {
console.log(data);
})
.catch(function(error) {
console.log(error);
});
请注意,这只是一个简单的示例,您可能需要根据您的需求进行适当的修改和错误处理。
原文地址: https://www.cveoy.top/t/topic/bKYG 著作权归作者所有。请勿转载和采集!