JavaScript HTTP 请求:Fetch API 和 XMLHttpRequest 详解
使用 JavaScript 发出 HTTP 请求可以使用内置的fetch函数或XMLHttpRequest对象。
使用fetch函数:
fetch(url, {
method: 'GET', // 请求方法,可以是'GET'、'POST'、'PUT'等
headers: {
'Content-Type': 'application/json' // 请求头,根据需要设置
},
// 其他选项,如请求体、认证信息等,根据需要设置
})
.then(response => response.json()) // 处理响应数据,这里假设响应是JSON格式
.then(data => {
// 对响应数据进行处理
console.log(data);
})
.catch(error => {
// 处理错误
console.error(error);
});
使用XMLHttpRequest对象:
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true); // 设置请求方法和URL
xhr.setRequestHeader('Content-Type', 'application/json'); // 设置请求头,根据需要设置
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) { // 请求完成
if (xhr.status === 200) { // 请求成功
var data = JSON.parse(xhr.responseText); // 处理响应数据,这里假设响应是JSON格式
console.log(data);
} else { // 请求失败
console.error('Request failed. Status:', xhr.status);
}
}
};
// 其他选项,如请求体、认证信息等,根据需要设置
xhr.send(); // 发送请求
请注意,以上示例中的url是你要请求的URL地址,你可以将其替换为实际的URL。同时,对于POST请求,你还需要设置请求体等相关参数。
原文地址: https://www.cveoy.top/t/topic/UEy 著作权归作者所有。请勿转载和采集!