JavaScript HTTP 请求: Fetch API 和 XMLHttpRequest
要使用JavaScript发出HTTP请求,您可以使用内置的Fetch API或XMLHttpRequest对象。以下是使用这两种方法的示例代码:
使用Fetch API:
fetch('https://api.example.com/data', {
method: 'GET', // 或者 'POST', 'PUT', 'DELETE'等
headers: {
'Content-Type': 'application/json', // 根据需要设置适当的Content-Type
// 其他自定义标头
},
// 可选:如果需要在请求正文中发送数据,则使用以下属性
// body: JSON.stringify({ key: 'value' }),
})
.then(response => response.json())
.then(data => {
// 处理从服务器返回的数据
console.log(data);
})
.catch(error => {
// 处理错误
console.error('发生错误:', error);
});
使用XMLHttpRequest对象:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true); // 或者 'POST', 'PUT', 'DELETE'等
xhr.setRequestHeader('Content-Type', 'application/json'); // 根据需要设置适当的Content-Type
// 可选:如果需要在请求正文中发送数据,则使用以下行
// xhr.send(JSON.stringify({ key: 'value' }));
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 400) {
var data = JSON.parse(xhr.responseText);
// 处理从服务器返回的数据
console.log(data);
} else {
// 处理错误
console.error('发生错误:', xhr);
}
};
xhr.onerror = function() {
// 处理错误
console.error('发生错误:', xhr);
};
xhr.send();
根据您的具体需求和服务器端点的要求,您可以根据需要设置其他选项和标头。请注意,这只是基本示例,您可以根据您的要求进行更多自定义和错误处理。
原文地址: https://www.cveoy.top/t/topic/cUki 著作权归作者所有。请勿转载和采集!