JavaScript HTTP 请求:XMLHttpRequest 和 fetch 函数指南
使用 JavaScript 发出 HTTP 请求可以使用内置的 'XMLHttpRequest' 对象或者更现代的 'fetch' 函数。下面是使用这两种方法的示例:
使用 '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 = xhr.responseText;
console.log(response);
}
};
// 发送请求
xhr.send();
使用 'fetch' 函数:
fetch('https://api.example.com/data')
.then(function (response) {
if (response.ok) {
// 请求成功
return response.text();
} else {
// 请求失败
throw new Error('请求失败:' + response.status);
}
})
.then(function (data) {
// 处理返回的数据
console.log(data);
})
.catch(function (error) {
// 处理错误
console.log(error);
});
这些代码片段可以帮助您使用 JavaScript 发出 HTTP 请求。请注意,这只是基本示例,您可能需要根据实际情况进行修改和适配。
原文地址: https://www.cveoy.top/t/topic/3KD 著作权归作者所有。请勿转载和采集!