JavaScript HTTP 请求:XMLHttpRequest 和 fetch() 方法
在 JavaScript 中,可以使用内置的 XMLHttpRequest 对象或者更现代的 fetch() 函数来发出 HTTP 请求。下面是使用这两种方法的示例代码:
使用 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() 函数:
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);
});
这些代码示例分别发送 GET 请求,并在收到响应后将其解析为 JSON 格式,并将结果打印到控制台。
请注意,在实际使用中,可能还需要处理请求的其他方面,例如设置请求头、发送 POST 请求或处理错误等。这些示例只是基本的 HTTP 请求方法。
原文地址: https://www.cveoy.top/t/topic/RtE 著作权归作者所有。请勿转载和采集!