JavaScript HTTP 请求:XMLHttpRequest 与 Fetch API
使用 JavaScript 发出 HTTP 请求通常需要使用浏览器内置的 XMLHttpRequest 对象或者现代的 fetch API。以下是使用这两种方法之一的示例:
使用 XMLHttpRequest 对象:
function makeHttpRequest(url, method, data, 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(data);
}
// 示例用法
var url = 'https://api.example.com/data';
var method = 'GET'; // 或者 'POST'
var data = null; // 如果是POST请求,可以设置请求体数据
var callback = function (response) {
console.log(response);
};
makeHttpRequest(url, method, data, callback);
使用 fetch API:
function makeHttpRequest(url, method, data, callback) {
var options = {
method: method,
headers: {
'Content-Type': 'application/json'
}
};
if (data) {
options.body = JSON.stringify(data);
}
fetch(url, options)
.then(function (response) {
return response.text();
})
.then(function (text) {
callback(text);
});
}
// 示例用法
var url = 'https://api.example.com/data';
var method = 'GET'; // 或者 'POST'
var data = null; // 如果是POST请求,可以设置请求体数据
var callback = function (response) {
console.log(response);
};
makeHttpRequest(url, method, data, callback);
请注意,这只是一个基本示例,具体的实现可能因为使用的框架、库或特定的API而有所不同。
原文地址: https://www.cveoy.top/t/topic/Rp9 著作权归作者所有。请勿转载和采集!