JavaScript HTTP 请求:XMLHttpRequest 和 fetch 函数
使用 JavaScript 发送 HTTP 请求可以使用内置的 XMLHttpRequest 对象或者使用 fetch 函数。以下是使用这两种方法之一发送 GET 请求的示例代码:
使用 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);
});
以上代码演示了如何向https://api.example.com/data发送 GET 请求,并在控制台打印响应数据。你可以根据需要修改 URL 和其他请求参数。
原文地址: https://www.cveoy.top/t/topic/QoW 著作权归作者所有。请勿转载和采集!