JavaScript HTTP 请求:XMLHttpRequest 和 Fetch API
使用 JavaScript 发送 HTTP 请求的常见方法是使用内置的 'XMLHttpRequest' 对象或者使用 'fetch()' 函数。
使用 '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' 请求发送到 'https://api.example.com/data',并在成功后打印响应数据。你可以根据你的实际需求进行适当的更改和扩展。
原文地址: https://www.cveoy.top/t/topic/O8b 著作权归作者所有。请勿转载和采集!