JavaScript 发送 HTTP 请求:XMLHttpRequest 和 Fetch 函数
要使用 JavaScript 发出 HTTP 请求,您可以使用内置的 XMLHttpRequest 对象或 fetch 函数。以下是使用这两种方法之一发送 HTTP 请求的示例:
使用 XMLHttpRequest 对象:
// 创建一个新的 XMLHttpRequest 对象
var xhr = new XMLHttpRequest();
// 设置请求的类型和 URL
xhr.open('GET', 'https://example.com/api/endpoint', true);
// 设置请求头(可选)
xhr.setRequestHeader('Content-Type', 'application/json');
// 处理响应
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var response = JSON.parse(xhr.responseText);
// 在这里处理响应数据
}
};
// 发送请求
xhr.send();
使用 fetch 函数:
// 发送 GET 请求
fetch('https://example.com/api/endpoint')
.then(response => response.json())
.then(data => {
// 在这里处理响应数据
})
.catch(error => {
// 处理错误
});
// 发送 POST 请求
fetch('https://example.com/api/endpoint', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ key: 'value' }) // 可选,如果需要发送数据
})
.then(response => response.json())
.then(data => {
// 在这里处理响应数据
})
.catch(error => {
// 处理错误
});
请记住,这只是发送 HTTP 请求的基本示例。您可以根据自己的需求对请求进行进一步配置和处理。
原文地址: https://www.cveoy.top/t/topic/bRBo 著作权归作者所有。请勿转载和采集!