JavaScript HTTP 请求:XMLHttpRequest 和 Fetch API 教程
使用 JavaScript 发出 HTTP 请求可以使用内置的 XMLHttpRequest 对象或者使用现代的 fetch API。下面是使用各种方法进行 HTTP 请求的示例:
使用 XMLHttpRequest 对象:
function makeRequest(url, method, callback) {
var xhr = new XMLHttpRequest();
xhr.open(method, url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
callback(xhr.responseText);
}
};
xhr.send();
}
// 发送 GET 请求
makeRequest('https://api.example.com/data', 'GET', function (response) {
console.log(response);
});
// 发送 POST 请求
makeRequest('https://api.example.com/data', 'POST', function (response) {
console.log(response);
});
使用 fetch API:
// 发送 GET 请求
fetch('https://api.example.com/data')
.then(function (response) {
return response.json();
})
.then(function (data) {
console.log(data);
})
.catch(function (error) {
console.log(error);
});
// 发送 POST 请求
fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ key: 'value' }),
})
.then(function (response) {
return response.json();
})
.then(function (data) {
console.log(data);
})
.catch(function (error) {
console.log(error);
});
注意:以上代码只是示例,你需要根据自己的需求和 API 文档进行适当的更改和错误处理。
原文地址: https://www.cveoy.top/t/topic/N3z 著作权归作者所有。请勿转载和采集!